尝试将扩展名应用于PAT时,不符合协议错误 [英] Doesn't conform to protocol error when trying to apply extension with PAT
问题描述
import Foundation
导入simd
$我不明白为什么这样做会失败b $ b协议TestProtocol {
associatedtype ElementType
func reduce_add(x:Self) - > ElementType
}
扩展名float2:TestProtocol {
typealias ElementType = Float
}
我在Playground中得到一个Type'float2'不符合协议'TestProtocol'的错误。具体来说,它告诉我:
Playground执行失败:Untitled Page.xcplaygroundpage:3:1:
error:type'float2'不符合协议'TestProtocol'
扩展名float2:TestProtocol {^ Untitled
$ b Page.xcplaygroundpage:6:10:note:protocol requires function
'reduce_add',类型为'float2 - > ElementType'
func reduce_add(x:Self) - > ElementType
/ //矢量元素的总和。
@warn_unused_result
public func reduce_add(x:float2) - >浮动
如果我调用 reduce_add(float2(2.4,3.1))
,我得到正确的结果。 ElementType是 typealias
编辑到浮动
。
我在这里错了吗?
public func reduce_add(x:float2) - >来自
simd
模块的浮动
是一个全局函数,而你的协议
需要一个实例方法。
你不能要求存在具有协议的全局功能。
如果你想要一个实例方法,那么它可能看起来像这样:
protocol TestProtocol {
associatedtype ElementType
func reduce_add() - > ElementType
}
扩展名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
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?
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
这篇关于尝试将扩展名应用于PAT时,不符合协议错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!