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
257 views
in Technique[技术] by (71.8m points)

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

Currently, I have an array of objects like this:

var myArr = [
  MyObject(name: "Abc", description: "Lorem ipsum 1."),
  MyObject(name: "Def", description: "Lorem ipsum 2."),
  MyObject(name: "Xyz", description: "Lorem ipsum 3.")
]

I am testing if an object exists before proceeding like this:

let item = myArr.filter { $0.name == "Def" }.first
if item != nil {
  // Do something...
}

But I'm looking for a shorter way to do this since I am doing this a lot. I'd like to do something like this but it is invalid:

if myArr.contains { $0.name == "Def" } {
  // Do something...
}

Is there any shorthand syntax I'm missing or a better way to do this?

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

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")
}

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

...