检查自定义对象数组是否包含特定自定义对象 [英] Checking if an array of custom objects contain a specific custom object
问题描述
说我有一个非常简单的Person
类
say i have a very simple Person
class
class Person {
var name:String
init(name:String) {
self.name = name
}
}
并且我希望将此类 Person
的集合存储在一个属性中,该属性是一个 People 类的 Person 类型的数组
and i wish to store a collections of such Person
s in a property, which is an array with type Person, of a People class
class People {
var list:[Person] = []
}
也许我是这样实现的
var alex = Person(name:"Alex")
var people = People()
people.list.append(alex)
问题:我如何检查 people.list 是否包含实例 alex?
QUESTION: how do i check if people.list contains the instance alex, please?
我的简单尝试,我希望返回 true
my simple attempt, which i was hoping to return true
people.list.contains(alex)
调用错误无法将'Person'类型的值转换为预期的参数类型'@noescape (Person) throws -> Bool'"
推荐答案
有两个contains
函数:
extension SequenceType where Generator.Element : Equatable {
/// Return `true` iff `element` is in `self`.
@warn_unused_result
public func contains(element: Self.Generator.Element) -> Bool
}
extension SequenceType {
/// Return `true` iff an element in `self` satisfies `predicate`.
@warn_unused_result
public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
}
编译器抱怨是因为编译器知道Person
不是Equatable
,因此contains
需要有一个谓词
但 alex
不是谓词.
The compiler is complaining because the compiler knows that Person
is not Equatable
and thus contains
needs to have a predicate
but alex
is not a predicate.
如果您数组中的人是 Equatable
(他们不是),那么您可以使用:
If the people in your array are Equatable
(they aren't) then you could use:
person.list.contains(alex)
由于它们不相等,您可以使用第二个 contains
函数:
Since they aren't equatable, you could use the second contains
function with:
person.list.contains { $0.name == alex.name }
或者,正如 Martin R 指出的,基于身份":
or, as Martin R points out, based on 'identity' with:
person.list.contains { $0 === alex }
或者您可以使 Person
成为 Equatable
(基于 name
或身份).
or you could make Person
be Equatable
(based on either name
or identity).
这篇关于检查自定义对象数组是否包含特定自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!