我想使用Accelerate框架来扩展Float和Double,但是每一个都需要不同的实现。
我尝试了显而易见的方法:
extension Array<Float> {
}并得到这个错误:
“必须使用由”where“子句指定的约束在非专用化的泛型类型”Array“上声明受约束的扩展”
以这种方式扩展Swift 2中的泛型类型是可能的吗?
现在,我已经让代码正常工作了。下面是一个使用加速框架进行求和的例子。
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
}
}发布于 2016-01-08 16:20:47
如果您只想扩展具有特定类型数组。您应该扩展_ArrayType协议。
extension _ArrayType where Generator.Element == Int {
func doSomething() {
...
}
}如果你扩展Array,你只能确保你的元素符合其他协议。即:
extension Array where Element: Equatable {
func doSomething() {
...
}
}更新:使用Swift 3.1 https://github.com/apple/swift/blob/master/CHANGELOG.md
extension Array where Element == Int {
func doSomething() {
...
}
}发布于 2016-09-29 07:06:20
斯威夫特3来营救!!
extension Collection where Iterator.Element == Int {
// `Collection` can be `Sequence`, etc
}发布于 2015-08-04 18:30:03
怎么样
extension CollectionType where Generator.Element == Double {
}或者,如果你想要更多:
protocol ArithmeticType {
func +(lhs: Self, rhs: Self) -> Self
func -(lhs: Self, rhs: Self) -> Self
func *(lhs: Self, rhs: Self) -> Self
func /(lhs: Self, rhs: Self) -> Self
}
extension Double : ArithmeticType {}
extension Float : ArithmeticType {}
extension SequenceType where Generator.Element : protocol<FloatLiteralConvertible, ArithmeticType> {
var sum : Generator.Element {
return reduce(0.0, combine: +)
}
var product : Generator.Element {
return reduce(1.0, combine: *)
}
}
stride(from: 1.0, through: 10.0, by: 1.0).sum // 55
[1.5, 2.0, 3.5, 4.0, 5.5].product // 231适用于Double和Float或符合ArithmeticType和FloatLiteralConvertible协议的任何其他类型。如果您需要访问数组的特定索引,请将SequenceType更改为CollectionType,因为您不能对序列执行此操作。
https://stackoverflow.com/questions/31806324
复制相似问题