I want to iterate over an array of arrays so search for a specific item and return true if exits.
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 there a shorter version using .map and avoiding for object in mainArray ? like mainArray.map.filter... ?
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 was pointed out by @AirspeedVelocity, you can actually make those closures have shorthand arguments:
func search() -> Bool {
return contains(mainArray) { contains($0) { $0 == "john" } }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With