我想迭代一个数组,所以搜索一个特定的项,如果退出则返回true。

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()

这是可行的,但是有一个较短的版本在使用.map并避免在mainarray中使用对象?
像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") }
}

或者,在Swift 1中:
func search() -> Bool {
  return contains(mainArray) {
    inner in contains(inner) {
      $0 == "john"
    }
  }
}

正如@airspeedvelocity所指出的,实际上可以使这些闭包具有速记参数:
func search() -> Bool {
  return contains(mainArray) { contains($0) { $0 == "john" } }
}

10-08 05:26