gpt4 book ai didi

swift - 尝试使用 PAT 应用扩展时出现不符合协议(protocol)错误

转载 作者:行者123 更新时间:2023-11-30 10:03:15 24 4
gpt4 key购买 nike

我不明白为什么会失败:

import Foundation
import simd

protocol TestProtocol {
associatedtype ElementType
func reduce_add(x:Self) -> ElementType
}

extension float2 : TestProtocol {
typealias ElementType=Float
}

我在 Playground 中收到“类型‘float2’不符合协议(protocol)‘TestProtocol’”错误。具体来说,它告诉我:

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

但是,当我查看 simd 界面时,我看到:

/// Sum of the elements of the vector.
@warn_unused_result
public func reduce_add(x: float2) -> Float

如果我调用reduce_add(float2(2.4,3.1)),我会得到正确的结果。 ElementType 被typealias编辑为Float

我哪里出错了?

最佳答案

现有

public func reduce_add(x: float2) -> Float

来自 simd 模块是一个全局函数,并且您的协议(protocol)需要一个实例方法

您不能要求存在具有协议(protocol)的全局函数。如果您想要一个实例方法,那么它可能如下所示:

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

关于swift - 尝试使用 PAT 应用扩展时出现不符合协议(protocol)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37339438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com