【问题标题】:Checking if an array of custom objects contain a specific custom object检查自定义对象数组是否包含特定的自定义对象
【发布时间】:2015-12-29 00:52:12
【问题描述】:

说我有一个非常简单的Person

class Person {
    var name:String
    init(name:String) {
        self.name = name
    }
}

我希望将此类Persons 的集合存储在 People 类的属性中,该属性是 Person 类型的数组

class People {
    var list:[Person] = []
}

也许我是这样实现的

var alex = Person(name:"Alex")
var people = People()
people.list.append(alex)

问题:请问如何检查 people.list 是否包含实例 alex?

我的简单尝试,我希望返回 true

people.list.contains(alex)

调用错误"cannot convert value of type 'Person' to expected argument type '@noescape (Person) throws -> Bool'"

【问题讨论】:

    标签: swift


    【解决方案1】:

    有两个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 需要有一个predicatealex 不是谓词。

    如果您数组中的人是Equatable(他们不是),那么您可以使用:

    person.list.contains(alex)
    

    由于它们不相等,您可以使用第二个 contains 函数:

    person.list.contains { $0.name == alex.name }
    

    或者,正如 Martin R 所指出的,基于“身份”:

    person.list.contains { $0 === alex }
    

    或者您可以将Person 设为Equatable(基于name 或身份)。

    【讨论】:

    【解决方案2】:

    问题:请问如何检查 people.list 是否包含实例 alex?

    class Person 是一个引用类型var alex 是一个引用 到对象存储。 identical-to 运算符=== 检查两个常量或变量是否引用同一个实例 一类的。

    因此,为了检查列表是否包含 具体实例,使用基于谓词的contains() 方法,并与===比较实例:

    if people.list.contains({ $0 === alex }) {
        // ...
    }
    

    【讨论】:

    • 我们如何获取条件为真的索引?
    • 这真的是非常有用的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2013-08-10
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2019-03-31
    • 2012-06-20
    相关资源
    最近更新 更多