无法在 Swift Array 扩展中使用 contains [英] Unable to use contains within a Swift Array extension

查看:25
本文介绍了无法在 Swift Array 扩展中使用 contains的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个提供独特"方法的简单数组扩展.这是我目前所拥有的:

I am trying to write a simple Array extension that provides a 'distinct' method. Here is what I have so far:

extension Array {
  func distinct() -> T[] {
    var rtn = T[]()

    for x in self {
      var containsItem = contains(rtn, x)
      if !containsItem {
        rtn.append(x)
      }
    }
    return rtn
  }
 }

问题是'contains'语句失败如下:

The problem is that the 'contains' statement fails as follows:

找不到接受所提供参数的包含"的重载

Could not find an overload for 'contains' that accepts the supplied arguments

我很确定类型约束是正确的.有什么想法吗?

I am pretty sure the type constraints are correct. Any ideas?

推荐答案

Swift 1.x

array 中的元素不必是 Equatable,即它们不能与 == 进行比较.

Swift 1.x

The elements in an array don't have to be Equatable, i.e. they don't have be comparable with ==.

这意味着您不能为所有可能的数组编写该函数.Swift 不允许你只扩展数组的一个子集.

That means you can't write that function for all possible Arrays. And Swift doesn't allow you to extend just a subset of Arrays.

这意味着您应该将其编写为一个单独的函数(这可能也是 contains 不是方法的原因).

That means you should write it as a separate function (and that's probably why contains isn't a method, either).

let array = ["a", "b", "c", "a"]

func distinct<T: Equatable>(array: [T]) -> [T] {
    var rtn = [T]()

    for x in array {
        var containsItem = contains(rtn, x)
        if !containsItem {
            rtn.append(x)
        }
    }
    return rtn
}

distinct(array) // ["a", "b", "c"]

Swift 2/Xcode 7(测试版)的更新

Swift 2 支持将扩展限制为协议实现的子集,因此现在允许以下内容:

Update for Swift 2/Xcode 7 (Beta)

Swift 2 supports restricting extensions to a subset of protocol implementations, so the following is now allowed:

let array = ["a", "b", "c", "a"]

extension SequenceType where Generator.Element: Comparable {
    func distinct() -> [Generator.Element] {
        var rtn: [Generator.Element] = []

        for x in self {
            if !rtn.contains(x) {
                rtn.append(x)
            }
        }
        return rtn
    }
}

array.distinct() // ["a", "b", "c"]

注意苹果是如何使用相同的语法添加 SequenceType.contains 的.

Note how apple added SequenceType.contains using the same syntax.

这篇关于无法在 Swift Array 扩展中使用 contains的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆