在Swift中使用where子句扩展数组类型 [英] Extend array types using where clause in Swift

查看:631
本文介绍了在Swift中使用where子句扩展数组类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用Accelerate框架来扩展[Float]和[Double],但每一个都需要不同的实现。



我试过很明显的:

 扩展数组< Float> {b $ b} 

并得到这个错误:


约束扩展必须在非特化通用
类型'Array'中声明,约束由'where'子句指定

blockquote>

是否可以通过这种方式扩展Swift 2中的泛型类型?



我的代码工作为现在预计。下面是一个使用Accelerate框架进行总结的例子。

 扩展名_ArrayType其中Generator.Element == Float {

func quickSum() - > Float {
var result:Float = 0
如果var x = self as? [浮点数] {
vDSP_sve(& x,1,& result,vDSP_Length(x.count))
}
返回结果
}
}

扩展名_ArrayType其中Generator.Element ==双{

func quickSum() - >双{
var结果:Double = 0
如果var x = self as? [Double] {
vDSP_sveD(& x,1,& result,vDSP_Length(x.count))
}
返回结果
}
}


解决方案

如果只想扩展特定类型的数组。你应该扩展_ArrayType协议。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ (){
...
}
}

如果你扩展 Array ,你只能确保你的元素符合其他一些协议。即:

 扩展数组元素:可等值{

func doSomething(){
...
}
}

更新:
使用Swift 3.1
https://github.com/apple/swift /blob/master/CHANGELOG.md

 扩展数组元素== Int {

func doSomething(){
...
}
}


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
    }
}

解决方案

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

这篇关于在Swift中使用where子句扩展数组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆