2016-03-05 48 views
1

我想要做一个简单的任务来查找数组中是否存在(string)元素。 “contains”函数适用于一维数组,但不适用于二维数组。 有什么建议吗? (此功能的文档显得稀疏,或者我不知道去哪里找。)Swift 2使用包含多维数组的函数

回答

2

更新了斯威夫特3

flatten方法已更名为joined现在。所以用法是

[[1, 2], [3, 4], [5, 6]].joined().contains(3) // true 

对于多维数组,你可以使用flatten降低一个维度。因此,对于二维数组:

[[1, 2], [3, 4], [5, 6]].flatten().contains(7) // false 

[[1, 2], [3, 4], [5, 6]].flatten().contains(3) // true 
0

不如J.Wangs回答,但另一种选择 - 你可以将列表减少使用减少一个布尔值(,结合:)功能。

[[1,2], [3,4], [5,6]].reduce(false, combine: {$0 || $1.contains(4)}) 
3

的夫特标准库不具有“多维数组”, 但是如果参考“嵌套的数组”(即一个阵列的阵列),那么 嵌套将工作,例如:

let array = [["a", "b"], ["c", "d"], ["e", "f"]] 
let c = array.contains { $0.contains("d") } 
print(c) // true 

这里内方法是

public func contains(element: Self.Generator.Element) -> Bool 

和外contains()方法是谓词基于

public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool 

其作为给定元素在内部阵列之一 发现尽快返回true

这种方法可以推广到更深的嵌套级别。

+0

谢谢! Swift文档确实涉及多维数组,但没有提供有关使用它们的很多信息。 – geoffry

+0

这应该是一个被接受的答案。 – user1366265

0

你也可以写一个扩展(SWIFT 3):

extension Sequence where Iterator.Element: Sequence { 
    func contains2D(where predicate: (Self.Iterator.Element.Iterator.Element) throws -> Bool) rethrows -> Bool { 
     return try contains(where: { 
      try $0.contains(where: predicate) 
     }) 
    } 
}