[英]Cannot pass protocol to function with constrained generic type
If you have a function which has a generic type that is constrained to a protocol you cannot pass a value of the type of the protocol to the function: 如果您的函数具有受限于协议的泛型类型,则无法将协议类型的值传递给该函数:
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)'
If I change the protocol to a class (and using inheritance instead) the same function would be executed in both cases. 如果我将协议更改为类(并改为使用继承),则在两种情况下都将执行相同的功能。
In addition "The Swift Programming Language" book says that 另外,《 The Swift Programming Language》这本书说
The colon in the declaration means “…of type…,” 声明中的冒号表示“ ...类型...”,
If this is also true for generic constraints I would argue it is a bug. 如果对于通用约束也是如此,我会认为这是一个错误。
So should this be considered a bug? 因此,应该将其视为错误吗? Or is there any case where it is useful to have this behavior? 还是在任何情况下有此行为有用?
Yes, per the spec on the definition of Types section: 是的,根据有关“ 类型 ”定义的规范:
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 . 命名类型包括类,结构,枚举和协议 。
protocols are a valid, named type. 协议是有效的命名类型。
Also supported by the fact that if you remove the P
constraint from testP
, the code compiles. 如果从testP
删除P
约束,则代码testP
编译,这也得到了支持。
You can resolve your scenario by changing the signature of testP to 您可以通过将testP的签名更改为来解决您的情况
func testP(value: P) {}
which should work for most scenarios. 适用于大多数情况。
Incidentally, your scenario is possible in C# where interfaces are similar to protocols in Swift 顺便说一下,您的方案在C#中是可行的,其中的接口类似于Swift中的协议
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.