- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果您的函数具有受协议(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/
考虑一个相关矩阵 r,表示变量 1 到 10 之间的相关性: r thr)) NA else sum(score[x]) }) min(summed_score, na.rm=T) ## [1] 1
我在 firebase 中有一个值需要增加,它受竞争条件的影响,所以我更愿意一次完成所有这些。 node: { clicks: 3 } 我需要设置 clicks = cli
我是一名优秀的程序员,十分优秀!