问题
I don't understand why this is failing:
import Foundation
import simd
protocol TestProtocol {
associatedtype ElementType
func reduce_add(x:Self) -> ElementType
}
extension float2 : TestProtocol {
typealias ElementType=Float
}
I get a "Type 'float2' does not conform to protocol 'TestProtocol'" error in the Playground. Specifically it tells me:
Playground execution failed: Untitled Page.xcplaygroundpage:3:1: error: type 'float2' does not conform to protocol 'TestProtocol' extension float2 : TestProtocol { ^ Untitled
Page.xcplaygroundpage:6:10: note: protocol requires function 'reduce_add' with type 'float2 -> ElementType' func reduce_add(x:Self) -> ElementType
When I look at the simd
interface, however, I see:
/// Sum of the elements of the vector.
@warn_unused_result
public func reduce_add(x: float2) -> Float
and if I call reduce_add(float2(2.4,3.1))
, I get the right result. ElementType is typealias
ed to Float
.
Where am I going wrong here?
回答1:
The existing
public func reduce_add(x: float2) -> Float
from the simd
module is a global function, and your protocol
requires an instance method.
You cannot require the existence of a global function with a protocol. If you want an instance method then it could look like this:
protocol TestProtocol {
associatedtype ElementType
func reduce_add() -> ElementType
}
extension float2 : TestProtocol {
func reduce_add() -> Float {
return simd.reduce_add(self)
}
}
let f2 = float2(2.4, 3.1)
let x = f2.reduce_add()
print(x) // 5.5
来源:https://stackoverflow.com/questions/37339438/doesnt-conform-to-protocol-error-when-trying-to-apply-extension-with-pat