【发布时间】:2016-03-05 08:22:46
【问题描述】:
我正在尝试查找数组中是否存在(字符串)元素的简单任务。 “包含”函数适用于一维数组,但不适用于二维数组。 有什么建议么? (关于这个函数的文档似乎很少,或者我不知道去哪里找。)
【问题讨论】:
标签: swift multidimensional-array
我正在尝试查找数组中是否存在(字符串)元素的简单任务。 “包含”函数适用于一维数组,但不适用于二维数组。 有什么建议么? (关于这个函数的文档似乎很少,或者我不知道去哪里找。)
【问题讨论】:
标签: swift multidimensional-array
Swift 标准库没有“多维数组”,
但如果你指的是“嵌套数组”(即数组数组),那么
嵌套的 contains() 可以工作,例如:
let array = [["a", "b"], ["c", "d"], ["e", "f"]]
let c = array.contains { $0.contains("d") }
print(c) // true
这里的内部contains()方法是
public func contains(element: Self.Generator.Element) -> Bool
而外部的contains() 方法是基于谓词的
public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
只要在一个元素中找到给定的元素就返回true
的内部数组。
这种方法可以推广到更深的嵌套级别。
【讨论】:
为 Swift 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
【讨论】:
不如 J.Wangs 的回答好,而是另一种选择 - 您可以使用 reduce(,combine:) 函数将列表缩减为单个布尔值。
[[1,2], [3,4], [5,6]].reduce(false, combine: {$0 || $1.contains(4)})
【讨论】:
你也可以写一个扩展(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)
})
}
}
【讨论】:
let array = [["a", "b"], ["c", "d"], ["e", "f"]]
var c = array.contains { $0.contains("d") }
print(c) // true
c = array.contains{$0[1] == "d"}
print(c) // true
c = array.contains{$0[0] == "c"}
print (c) // true
if let indexOfC = array.firstIndex(where: {$0[1] == "d"}) {
print(array[indexOfC][0]) // c
print(array[indexOfC][1]) // d
} else {
print ("Sorry, letter is not in position [][letter]")
}
if let indexOfC = array.firstIndex(where: {$0[0] == "c"}) {
print(array[indexOfC][1]) // d
print(array[indexOfC][0]) // c
} else {
print ("Sorry, letter is not in position [letter][]")
}
【讨论】: