Peter71 Peter71 - 6 months ago 41
Swift Question

Get shorter version of for loop?

I'm using Swift 3.0 and have this code for searching an item in an array as an extension of String type:

extension String {
func equal(compareToArray : [String]) -> Bool {
for s in compareToArray {
if self == s {
return true
}
}
return false
}
}


It runs fine, but my question is, can I do it better (shorter/more simple or faster)?

Okay, another similar sample:

func contains(compareToArray : [String]) -> Bool {
for s in compareToArray {
if self.contains(s) {
return true
}
}
return false
}

Answer

Shorter, simpler, faster

let compareToArray = ["foo", "bar", "baz"]
compareToArray.contains("bar")

Edit:

According to your second example

!compareToArray.filter{ $0.contains("oo") }.isEmpty

compareToArray.index(where: {$0.contains("oo")}) != nil