Swift 2使用“;包括「;多维数组函数
我试图完成一项简单的任务,即查找数组中是否存在(字符串)元素。“contains”函数适用于一维数组,但不适用于二维数组。 有什么建议吗?(关于此功能的文档似乎不多,或者我不知道从何处查找。)为Swift 3更新Swift 2使用“;包括「;多维数组函数,swift,multidimensional-array,Swift,Multidimensional Array,我试图完成一项简单的任务,即查找数组中是否存在(字符串)元素。“contains”函数适用于一维数组,但不适用于二维数组。 有什么建议吗?(关于此功能的文档似乎不多,或者我不知道从何处查找。)为Swift 3更新 plant方法现在已重命名为joined。所以用法应该是 [[1, 2], [3, 4], [5, 6]].joined().contains(3) // true 对于多维数组,可以使用展平减小一维。对于二维数组: [[1, 2], [3, 4], [5, 6]].flatten
plant
方法现在已重命名为joined
。所以用法应该是
[[1, 2], [3, 4], [5, 6]].joined().contains(3) // true
对于多维数组,可以使用
展平
减小一维。对于二维数组:
[[1, 2], [3, 4], [5, 6]].flatten().contains(7) // false
[[1, 2], [3, 4], [5, 6]].flatten().contains(3) // true
不像J.Wang的答案那么好,但还有另一种选择-您可以使用reduce(,combine:)函数将列表缩减为单个布尔值
[[1,2], [3,4], [5,6]].reduce(false, combine: {$0 || $1.contains(4)})
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):
谢谢Swift文档确实提到了多维数组,但没有提供关于使用多维数组的太多信息。请不要只发布代码作为答案,还要解释代码的作用以及如何解决问题。带有解释的答案通常更有帮助,质量更好,更容易吸引选票。
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][]")
}