使用带过滤器的地图

时间:2015-07-03 10:14:14

标签: swift

我想迭代一个数组数组,以便搜索特定的项目,如果退出则返回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 ......?

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

我知道这不使用地图和过滤器,但为什么不使用包含?

func search() -> Bool {
    for object in mainArray {
        if contains(object, "john") {
           return true
        }
    }
    return false
}