Using a filter map
I want to loop over an array of arrays to find a specific element and return true if exited.
var fruits = ["apple", "banana"]
var names = ["ivan", "john", "maria"]
var mainArray = [fruits, names]
// i want to return true if theres a name/fruit that is "john"
func search() -> Bool {
for object in mainArray {
if (object.filter { $0 == "john" }).count > 0 {
return true
}
}
return false
}
search()
This works, but is there a shorter version using .map and an exception for the object in mainArray? how is mainArray.map.filter ...?
+3
source to share
2 answers
var fruits = ["apple", "banana"]
var names = ["ivan", "john", "maria"]
var mainArray = [fruits, names]
func search() -> Bool {
return mainArray.contains { $0.contains("john") }
}
Or in Swift 1:
func search() -> Bool {
return contains(mainArray) {
inner in contains(inner) {
$0 == "john"
}
}
}
As @AirspeedVelocity pointed out, you can actually make these closures have shorthand arguments:
func search() -> Bool {
return contains(mainArray) { contains($0) { $0 == "john" } }
}
+5
source to share