gpt4 book ai didi

swift - 无法将协议(protocol)传递给具有受约束泛型类型的函数

转载 作者:行者123 更新时间:2023-11-30 10:12:38 25 4
gpt4 key购买 nike

如果您的函数具有受协议(protocol)约束的泛型类型,则无法将协议(protocol)类型的值传递给函数:

protocol P {}

extension Int: P {}

func testP<T: P>(value: T) {}

// passing Int
let val = 0
testP(val)

// passing Int as P (protocol)
let valAsP: P = 0
testP(valAsP) // error: cannot invoke 'testP' with an argument list of type '(P)'

如果我将协议(protocol)更改为类(并使用继承),则在两种情况下都会执行相同的函数。

此外,《Swift 编程语言》一书还提到了这一点

The colon in the declaration means “…of type…,”

如果对于通用约束也是如此,我认为这是一个错误。

那么这应该被视为一个错误吗?或者在任何情况下这种行为是有用的吗?

最佳答案

是的,根据 Types 定义的规范部分:

A named type is a type that can be given a particular name when it is defined. Named types include classes, structures, enumerations, and protocols.

协议(protocol)是有效的命名类型。

事实也证明了这一点:如果您从 testP 中删除 P 约束,代码就会编译。

您可以通过将 testP 的签名更改为来解决您的情况

func testP(value: P) {}

这应该适用于大多数场景。

顺便说一下,您的场景是 possible in C#其中接口(interface)类似于 Swift 中的协议(protocol)

我创建了问题 SR-1324

关于swift - 无法将协议(protocol)传递给具有受约束泛型类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130027/

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