【问题标题】:Swift 2 Using "contains" function with multidimensional arraySwift 2 将“包含”函数与多维数组一起使用
【发布时间】:2016-03-05 08:22:46
【问题描述】:

我正在尝试查找数组中是否存在(字符串)元素的简单任务。 “包含”函数适用于一维数组,但不适用于二维数组。 有什么建议么? (关于这个函数的文档似乎很少,或者我不知道去哪里找。)

【问题讨论】:

    标签: swift multidimensional-array


    【解决方案1】:

    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 文档确实提到了多维数组,但没有提供太多关于使用它们的信息。
    【解决方案2】:

    为 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】:

      不如 J.Wangs 的回答好,而是另一种选择 - 您可以使用 reduce(,combine:) 函数将列表缩减为单个布尔值。

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

      【讨论】:

        【解决方案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)
                })
            }
        }
        

        【讨论】:

          【解决方案5】:
          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][]")
          }
          

          【讨论】:

          • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
          猜你喜欢
          • 2013-04-13
          • 2014-03-06
          • 1970-01-01
          • 1970-01-01
          • 2012-12-13
          • 2013-01-09
          • 2021-12-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多