Swift 2中如何使用"contains"函数处理多维数组?

3

我想做一个简单的任务,就是查找一个字符串元素是否存在于一个数组中。"contains"函数适用于一维数组,但不适用于二维数组。 有什么建议吗?(这个函数的文档似乎很少,或者我不知道在哪里找。)

5个回答

3

已更新至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

3
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文档确实提到了多维数组,但并没有提供太多有关使用它们的信息。 - geoffry

1

虽然不如J.Wang的答案好,但还有另一种选择 - 您可以使用reduce(,combine:)函数将列表减少到单个布尔值。

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

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

-1
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][]")
}

1
请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接