Checking if an array of custom objects contain a specific custom object

前端 未结 2 1632
春和景丽
春和景丽 2020-12-03 09:47

say i have a very simple Person class

class Person {
    var name:String
    init(name:String) {
        self.name = name
    }
}
相关标签:
2条回答
  • 2020-12-03 10:23

    QUESTION: how do i check if people.list contains the instance alex, please?

    class Person is a reference type, and var alex is a reference to the object storage. The identical-to operator === checks if two constants or variables refer to the same instance of a class.

    Therefore, in order to check if the list contains a specific instance, use the predicate-based contains() method, and compare instances with ===:

    if people.list.contains({ $0 === alex }) {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-03 10:42

    There are two contains functions:

    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
    }
    

    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.

    If the people in your array are Equatable (they aren't) then you could use:

    person.list.contains(alex)
    

    Since they aren't equatable, you could use the second contains function with:

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

    or, as Martin R points out, based on 'identity' with:

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

    or you could make Person be Equatable (based on either name or identity).

    0 讨论(0)
提交回复
热议问题