Doesn't conform to protocol error when trying to apply extension with PAT

守給你的承諾、 提交于 2019-12-12 02:26:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!