代码之家  ›  专栏  ›  技术社区  ›  mfaani

Swift有没有简单的方法来获取2d数组中的列?[副本]

  •  1
  • mfaani  · 技术社区  · 8 年前

    我想在Swift中扩展数组,以在2D数组的每个数组或列中返回单个元素。到目前为止,我已经:

    extension Array where // what goes here?
        func getColumn( column: Int ) -> [ Int ] {
            return self.map { $0[ column ] }
        }
    }
    

    我认为我需要在之后以某种方式指定2D数组 where ,但我一直无法找到正确的方法。

    指定后的2D数组的正确语法是什么 哪里 ?

    我还想知道是否有一个好的文档来说明如何在之后指定可用的内容 延长寿命。我在网上找不到 Apple's Swift extension documentation

    提前谢谢。

    0 回复  |  直到 10 年前
        1
  •  18
  •   Martin R    7 年前

    您需要约束 Element 数组的类型。下标方法在 CollectionType 协议:

    public protocol CollectionType : Indexable, SequenceType {
        // ...
        public subscript (position: Self.Index) -> Self.Generator.Element { get }
        // ...
    }
    

    因此,您可以为元素为集合的数组定义扩展方法:

    extension Array where Element : CollectionType {
        func getColumn(column : Element.Index) -> [ Element.Generator.Element ] {
            return self.map { $0[ column ] }
        }
    }
    

    let a = [[1, 2, 3], [4, 5, 6]]
    let c = a.getColumn(1)
    
    print(c) // [2, 5]
    

    extension Array where Element : CollectionType {
        subscript(column column : Element.Index) -> [ Element.Generator.Element ] {
            return map { $0[ column ] }
        }
    }
    
    let a = [["a", "b", "c"], [ "d", "e", "f" ]]
    let c = a[column: 2]
    print(c) // ["c", "f"]
    

    更新 Swift 3:

    extension Array where Element : Collection {
        func getColumn(column : Element.Index) -> [ Element.Iterator.Element ] {
            return self.map { $0[ column ] }
        }
    }
    

    或作为下标:

    extension Array where Element : Collection {
        subscript(column column : Element.Index) -> [ Element.Iterator.Element ] {
            return map { $0[ column ] }
        }
    }