Search code examples
swiftgenericsswift2swift-extensions

Extend array types using where clause in Swift


I'd like to use the Accelerate framework to extend [Float] and [Double] but each of these requires a different implementation.

I tried the obvious:

extension Array<Float> {
}

and get this error:

"Constrained extension must be declared on the unspecialised generic type 'Array' with constraints specified by a 'where' clause"

Is it posible to extend generic types in Swift 2 in this way?

I've got the code working as expected now. Here's an example showing a summation using the Accelerate framework.

extension _ArrayType where Generator.Element == Float {

    func quickSum() -> Float {
        var result: Float = 0
        if var x = self as? [Float] {
            vDSP_sve(&x, 1, &result, vDSP_Length(x.count))
        }
        return result
    }
}

extension _ArrayType where Generator.Element == Double {

    func quickSum() -> Double {
        var result: Double = 0
        if var x = self as? [Double] {
            vDSP_sveD(&x, 1, &result, vDSP_Length(x.count))
        }
        return result
    }
}

Solution

  • If you want to extend only array with specific type. You should extend _ArrayType protocol.

    extension _ArrayType where Generator.Element == Int {
    
       func doSomething() {
           ... 
       }
    }
    

    If you extend Array you can only make sure your element is conformed some protocol else. i.e:

    extension Array where Element: Equatable {
    
       func doSomething() {
           ... 
       }
    }
    

    Updated: With Swift 3.1 https://github.com/apple/swift/blob/master/CHANGELOG.md

    extension Array where Element == Int {
    
       func doSomething() {
           ... 
       }
    }