Shorthand to test if an object exists in an array for Swift?

Why not use the built-in contains() function? It comes in two flavors

func contains<S : SequenceType, L : BooleanType>(seq: S, predicate: @noescape (S.Generator.Element) -> L) -> Bool
func contains<S : SequenceType where S.Generator.Element : Equatable>(seq: S, x: S.Generator.Element) -> Bool

and the first one takes a predicate as argument.

if contains(myArr, { $0.name == "Def" }) {
    println("yes")
}

Update: As of Swift 2, both global contains() functions have
been replaced by protocol extension methods:

extension SequenceType where Generator.Element : Equatable {
    func contains(element: Self.Generator.Element) -> Bool
}

extension SequenceType {
    func contains(@noescape predicate: (Self.Generator.Element) -> Bool) -> Bool
}

and the first (predicate-based) one is used as:

if myArr.contains( { $0.name == "Def" }) {
    print("yes")
}

Swift 3:

if myArr.contains(where: { $0.name == "Def" }) {
    print("yes")
}

Leave a Comment