protocol EuclideanPoint {
func distance(other: Self) -> Double
func dimension() -> UInt
}
现在我想扩展[Float]和[Double]来采用该协议.
但是以下代码:
extension [Float]: EuclideanPoint {
func distance(other: [Float]) {
return Double(zip(self,other).map{a,b in pow(a-b,2)}.reduce(0,combine: +))
}
func dimension() {
return UInt(self.count)
}
}
因错误而无效
error: constrained extension must be declared on the unspecialized generic type ‘Array’ with constraints specified by a ‘where’ clause
我发现了类似的问题(如this),但建议的解决方案是使用扩展CollectionType,其中Generator.Element == S {…},但在此上下文中它会导致错误:
error: protocol ‘CollectionType’ can only be used as a generic constraint because it has Self or associated type requirements
这有什么解决方案吗?
编辑:
使用建议的解决方案:
protocol DoubleConvertibleType {
var doubleValue: Double { get }
}
extension Double : DoubleConvertibleType { var doubleValue: Double { return self } }
extension Float : DoubleConvertibleType { var doubleValue: Double { return Double(self) } }
extension CGFloat: DoubleConvertibleType { var doubleValue: Double { return Double(self) } }
extension Array where Element : DoubleConvertibleType {
func distance(other: Array) -> Double {
return Double(zip(self,other).map{ pow($0.0.doubleValue - $0.1.doubleValue,2) }.reduce(0,combine: +))
}
func dimension() -> UInt {
return UInt(self.count)
}
}
给[Double]和[Float] .distance()和.dimension()方法.然而,[Double]或[Float]不能用来代替符合EuclideanPoint协议所需的东西,产生错误:
error: type ‘[Double]’ does not conform to protocol ‘EuclideanPoint’
以下解决方案有些通用,符合协议EuclidianPoint,并基于两个假设:
>我们允许在EuclideanPoint协议中为方法距离的蓝图包含泛型类型约束,并且我们将使用泛型([T])而不是参数类型为Self.但是,我们将确定(在编译时)[T]与Self的相同类型(此处为[Double],[Float]或[Int]类型的Self),并确定[T]符合议程EuclidianPoint.
>您可以将我们的函数编程技术(例如.map和.reduce)保留在此特定应用程序之外,并且只关注实现“欧几里德协议采用的通用数组”. Swift中的这些.map,.reduce等功能确实很简洁实用,但在许多应用程序中只是for-hood-for循环的包装器,所以你不会因为手动命令式的风格而失去任何性能.事实上,已知.reduce由于重复的数组复制分配而执行非常不可选的,同时减少了数组(我不会在这里更多地介绍……).无论如何,也许你可以利用我的例子并将其调整回更具功能性的范例.
我们从一个自定义类型协议MyTypes开始,它将作为我们想要包含在我们的泛型中的类型的接口.我们还添加了略微更新的EuiclidianPoint协议,其中我们使用协议MyTypes作为距离(…)函数blue-print中使用的泛型T的类型约束.
/* Used as type constraint for Generator.Element */
protocol MyTypes {
func -(lhs: Self,rhs: Self) -> Self
func +=(inout lhs: Self,rhs: Self)
}
extension Int : MyTypes { }
extension Double : MyTypes { }
extension Float : MyTypes { }
/* Extend with the types you wish to be covered by the generic ... */
/* Used as extension to Array : blueprints for extension method
to Array where Generator.Element are constrainted to MyTypes */
protocol EuclideanPoint {
func distance<T: MyTypes> (other: [T]) -> Double?
func dimension() -> UInt
}
请注意,我已将Double返回距离更改为可选;您可以按照自己的意愿处理,但如果自身和其他数组的长度不同,或Self和[T]类型不同,则需要显示不符合 – 我将在此处使用nil.
我们现在可以通过EuclidianPoint协议实现我们对Array的扩展:
/* Array extension by EuclideanPoint protocol */
extension Array : EuclideanPoint {
func distance<T: MyTypes> (other: [T]) -> Double? {
/* [T] is Self? proceed,otherwise return nil */
if let a = self.first {
if a is T && self.count == other.count {
var mySum: Double = 0.0
for (i,sElement) in self.enumerate() {
mySum += pow(((sElement as! T) - other[i]) as! Double,2)
}
return sqrt(mySum)
}
}
return nil
}
func dimension() -> UInt {
return UInt(self.count)
}
}
请注意,在距离函数的内部if子句中,我们使用显式向下转换为T,但由于我们断言Self的元素是T类型,所以这没关系.
无论如何,有了这个,我们就完成了,我们可以测试我们的“通用”数组扩展,我们现在注意到它也符合你的协议EuclidianPoint.
/* Tests and Examples */
let arr1d : [Double] = [3.0,4.0,0.0]
let arr2d : [Double] = [-3.0,-4.0,0.0]
let arr3d : [Double] = [-3.0,-4.0]
let arr1f : [Float] = [-3.0,0.0]
let arr1i = [1,2,3]
let _a = arr1d.dimension() // 3,OK
let _b = arr1d.distance(arr2d) // 10,OK (A->B dist)
let _c = arr1d.distance(arr1f) // nil (Incomp. types)
let _d = arr1d.distance(arr3d) // nil (Incomp. sizes)
let _e = arr1i.distance(arr1d) // nil (Incomp. types)
/* for use in function calls: generic array parameters constrained to
those that conform to protocol 'EuclidianPoint',as requested */
func bar<T: MyTypes,U: protocol<EuclideanPoint,_ArrayType> where U.Generator.Element == T> (arr1: U,_ arr2: U) -> Double? {
// ...
return arr1.distance(Array(arr2))
/* We'll need to explicitly tell the distance function
here that we're sending an array,by initializing an
array using the Array(..) initializer */
}
let mydist = bar(arr1d,arr2d) // 10,OK
好!
我的第一个答案仍然留有一条说明:
通用类型数组扩展到协议实际上最近才在这里被问到:
> Extending typed array by conforming to a protocol in Swift 2
一致意见是你不能以一种你可能期望的“整洁的”方式对数组进行通用的扩展.然而,有一些模拟这种行为的解决方法,一种是我上面使用的那种行为.如果您对其他方法感兴趣,我建议您查看此主题.