扩展数组的数组 - Swift 4.1

5

扩展数组数组

Swift 4.1,Xcode 9.3

我该如何在Swift中扩展Array<Array>

extension Array where Element == Array { //This is where the error occurs
    someMethod()
}

此外,我想扩展一个特定类型的数组的数组,例如:
extension Array where Element == Array<Int> { //Can I even do this?
    someOtherMethod()
}

Thanks in advance for your help!


1
使用泛型编写 func filterWithId<T where T : Idable>() -> [T] { } 函数。 - a.masri
4个回答

5

您可以选择任一种方式进行扩展

extension Array where Element == Int {

    func someIntegers() {

    }
}

extension Array where Element == Array<String> {

    func someStrings() {

    }
}

并且可以在任何地方像这样调用:

[0, 1, 2].someIntegers()

[["hi"]].someStrings()

2

我曾使用过

extension Array where Element: RandomAccessCollection, Element.Index == Int {
}

例如,通过 IndexPath 添加自定义下标。

0

通用方法解决方案(Swift 5.5):

extension Collection where Element: Collection, Element.Element: Equatable, Element.Index == Int {

    // Returns aggregated count of all elements.
    func totalCount() -> Int {
        return reduce(into: 0) { partialResult, innerCollection in
            partialResult += innerCollection.count
        }
    }

    // Returns `IndexPath` for given `element` inside 2d array.
    func indexPath(for element: Element.Element) -> IndexPath? {
        for (section, innerCollection) in enumerated() {
            if let row = innerCollection.firstIndex(of: element) {
                return IndexPath(row: row, section: section)
            }
        }
        
        return nil
    }
}

0

对于想要以比目前所展示的答案更通用的方式进行操作的人来说,这是一个很好的开始。

扩展 Array<Array>

protocol ExpressibleAsDouble { // for illustration
    func asDouble() -> Double
}

extension Array where Element: Sequence, Element.Element: ExpressibleAsDouble {
    func asDoubles() -> [[Double]] {
        return self.map { row in
            row.map { scalar in
                scalar.asDouble()
            }
        }
    }
}

//-------------------------------------------
//example usage
extension Int: ExpressibleAsDouble {
    func asDouble() -> Double {
        return Double(self)
    }
}

let ints: [[Int]] = [[1, 2], [3, 4]]
print(ints.asDoubles())
// prints: [[1.0, 2.0], [3.0, 4.0]]

这实际上是扩展了Array<任何序列,其中Array是一种可能的选项>,如果您想通用地引用嵌套标量,我不确定是否可以将其限制为只有Array<Array>

Element指的是Array的第一维(另一个数组),而Element.Element指的是嵌套维度的类型(如果我们谈论的是二维数组,则为标量)。


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