问题描述
我最近在阅读。我的问题涉及博客中的以下两个示例:
代码:
protocol MyProtocol1 {
var myValue:Self {get}
}
let array:[MyProtocol1] = [] //错误。
产生错误:
这是预料之中的,有关这个话题的几个SO问题。但是,通过将 myValue
更改为函数不会有任何错误,但在两种情况下都会返回 Self
p>
protocol MyProtocol2 {
func myValue() - > Self
}
let array:[MyProtocol2] = [] //这没关系。
有人知道这个看似奇怪行为的原因吗?
这段视频解释了大约18分钟:
因为你的协议引用self,它只能用作通用约束而不是类型。
例子:
假设2个结构实现你的协议 - 杜克&安培;银。
如果您制作了一组protocol2([protocol2]),那么您的数组可能包含Dukes are Silvers。
myValue明确指出返回值必须是self。这意味着公爵必须退还公爵,而银必须退还银牌。因此,你不能拥有杜克斯& Silvers在同一个数组中,因为它们的MyValue函数具有不同的返回值。
要解决这个问题,您可以:
1)制作myValue协议2的返回类型,以便Dukes和Silvers都返回protocol2类型。2)制作一个符合协议2的泛型数组。
I was recently reading Protocols, Generic Type Constraints and Arrays in Swift. My question concerns the following two examples from the blog:
The code:
protocol MyProtocol1 {
var myValue: Self { get }
}
let array: [MyProtocol1] = [] // Error.
Produces the error:
That's expected and there have been several SO questions concerning the topic. However, by changing myValue
to a function there's no longer any error, yet in both cases Self
is returned.
protocol MyProtocol2 {
func myValue() -> Self
}
let array: [MyProtocol2] = [] // This is okay.
Does anyone know the cause of this seemingly strange behaviour?
It's explained about 18 minutes into this video:https://developer.apple.com/videos/wwdc/2015/?id=408
Because your protocol references "self" it can only be used as a generic constraint not as a type.
Example:Let's say 2 structs implement your protocol - Duke & Silver.
If you made an array of protocol2 ([protocol2]), then your array could contain either Dukes are Silvers.
myValue specifically states that the return value must be self. This means that a Duke must return a Duke and a Silver must return a Silver. As such, you can't have Dukes & Silvers in the same array because their MyValue functions have different return values.
To fix the issue, you can either:
1) Make the return type of myValue protocol2 so that Dukes and Silvers both just return a protocol2 type
2) Make an array of generics that conform to protocol2
这篇关于自协议的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!