簡體   English   中英

擴展 Arrays 的 Arrays - Swift 4.1

[英]Extending Arrays of Arrays - Swift 4.1

擴展 Arrays 的 Arrays

Swift 4.1,Xcode 9.3

如何在 Swift 中擴展Array<Array>

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

此外,我將如何擴展特定類型的 arrays 數組,例如:

extension Array where Element == Array<Int> { //Can I even do this?
    someOtherMethod()
}

在此先感謝您的幫助!

您可以以任何方式擴展

extension Array where Element == Int {

    func someIntegers() {

    }
}

extension Array where Element == Array<String> {

    func someStrings() {

    }
}

然后在任何地方這樣叫

[0, 1, 2].someIntegers()

[["hi"]].someStrings()

我用過

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

例如通過IndexPath添加自定義下標

對於想要比迄今為止所顯示的答案更通用的人來說,這是一個開始。

擴展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<any sequence, Array being one possible option> is Array<any sequence, Array being one possible option> ,如果您想一般地引用嵌套標量,我不確定您是否可以將其限制為Array<Array>

Element指的是Array的第一個維度(這是另一個 Array),而Element.Element指的是嵌套維度的類型(如果我們談論的是 2D 數組,則是標量)。

通用方法的解決方案(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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM