Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

generics - 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
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() {
       ... 
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...