Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

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

say i have a very simple Person class

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

and i wish to store a collections of such Persons in a property, which is an array with type Person, of a People class

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

perhaps i achieve this as follows

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

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

my simple attempt, which i was hoping to return true

people.list.contains(alex)

calls an error "cannot convert value of type 'Person' to expected argument type '@noescape (Person) throws -> Bool'"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...