Search code examples
arraysswiftwhere-clauseextension-methods

Extending Arrays of Arrays - Swift 4.1


Extend Arrays of Arrays

Swift 4.1, Xcode 9.3

How do I extend Array<Array> in Swift?

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

Furthermore, how would I extend an array of arrays of a specific type, for example:

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

Thanks in advance for your help!


Solution

  • You can extend in either way

    extension Array where Element == Int {
    
        func someIntegers() {
    
        }
    }
    
    extension Array where Element == Array<String> {
    
        func someStrings() {
    
        }
    }
    

    and call like this anywhere,

    [0, 1, 2].someIntegers()
    
    [["hi"]].someStrings()