【问题标题】:Get column from 2D array – how to restrict array type in extension?从二维数组中获取列——如何在扩展中限制数组类型?
【发布时间】:2019-04-01 05:53:07
【问题描述】:

我想在 Swift 中扩展 Array 以在每个数组或列中返回一个元素,用于 2D 数组。到目前为止,我有:

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

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

在where 之后指定二维数组的正确语法是什么?

我也很好奇是否有一个很好的文档来说明如何在扩展生命中指定where 之后可用的内容。我在Apple's Swift extension documentation 找不到那个

提前致谢。

【问题讨论】:

  • 我把标题改了一点,所以关于检索数组列的其他问题可以在这里重定向。

标签: arrays swift


【解决方案1】:

您需要约束数组的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 ] }
    }
}

【讨论】:

  • Swift 3:CollectionType 替换为 Collection 和 Generator 是 Iterator 所以我们有: extension Array where Element : Collection { func getColumn(column : Element.Index) -> [ Element.Iterator.Element ] { return self.map { $0[ 列 ] } } }
  • 1.对于 Swift4,您是否需要将 Generator 更新为 Iterator? 2. 通俗地说,你能告诉我为什么-> Element 不起作用,你需要做-> [ Element.Iterator.Element ] 吗?因为如果我这样做 -> Element 我会收到以下错误:无法将类型“[Element.Element]”的返回表达式转换为返回类型“元素”
  • @Honey:Swift 3 版本应该也可以在 Swift 4 中使用。
  • 它在 Xcode 9.4.1 上无法为我编译我收到以下错误:'Array.Element' 没有名为 'Generator' 的成员类型;您的意思是“生成器”吗? & “生成器”已重命名为“迭代器”并且也可以回答我的其他问题
  • @Honey:你是不是用了答案末尾的“Update for Swift 3”版本?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-14
  • 2010-11-09
  • 2019-10-09
  • 2021-12-07
  • 1970-01-01
相关资源
最近更新 更多