Swift 2 Array包含对象?

Mit*_*son 10 arrays contains swift

为什么这不起作用?我可以在String上使用array.contains()但它不适用于Object.

var array = ["A", "B", "C"]

array.contains("A") // True

class Dog {
    var age = 1
}

var dogs = [Dog(), Dog(), Dog()]
var sparky = Dog()
dogs.contains(sparky) // Error Cannot convert value of type 'Dog' to expected argument type '@noescape (Dog) throws -> Bool
Run Code Online (Sandbox Code Playgroud)

jer*_*e10 13

Dog需要实施Equatable.

class Dog: Equatable {

   var age = 1

}

func == (lhs: Dog, rhs: Dog) -> Bool {
      return lhs.age == rhs.age
}
Run Code Online (Sandbox Code Playgroud)


Sul*_*han 10

为了真正解释那里发生的事情,首先我们要了解有两种contains方法Array(或者更好地说,在SequenceType上).

func contains(_ element: Self.Generator.Element) -> Bool
Run Code Online (Sandbox Code Playgroud)

有约束

Generator.Element : Equatable
Run Code Online (Sandbox Code Playgroud)

func contains(@noescape _ predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
Run Code Online (Sandbox Code Playgroud)

第一个基本上是使用搜索数组中的给定元素==.第二个使用闭包返回a Bool来搜索元素.

第一种方法不能使用,因为Dog不采用Equatable.编译器尝试使用第二种方法但是有一个闭包作为参数,因此您看到的错误.

解决方案:实现EquatableDog.

如果您正在寻找对象引用比较,您可以使用一个简单的闭包:

let result = dogs.contains({ $0 === sparky })
Run Code Online (Sandbox Code Playgroud)