自协议的行为 [英] Behaviour of Protocols with Self

查看:91
本文介绍了自协议的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在阅读协议,泛型类型约束和Swift中的数组。我的问题涉及博客中的以下两个示例:



代码:

  protocol MyProtocol1 {
var myValue:Self {get}
}

let array:[MyProtocol1] = [] //错误。

产生错误:


Protocol'MyProtocol1'只能用作通用约束,因为
具有Self或相关类型要求。

这是预料之中的,有关这个话题的几个SO问题。但是,通过将 myValue 更改为函数不会有任何错误,但在两种情况下都会返回 Self p>

  protocol MyProtocol2 {
func myValue() - > Self
}

let array:[MyProtocol2] = [] //这没关系。

有人知道这个看似奇怪行为的原因吗?

这段视频解释了大约18分钟:
https://developer.apple.com/videos/wwdc/2015/?id=408



因为你的协议引用self,它只能用作通用约束而不是类型。

例子:
假设2个结构实现你的协议 - 杜克&安培;银。



如果您制作了一组protocol2([protocol2]),那么您的数组可能包含Dukes are Silvers。

myValue明确指出返回值必须是self。这意味着公爵必须退还公爵,而银必须退还银牌。因此,你不能拥有杜克斯& Silvers在同一个数组中,因为它们的MyValue函数具有不同的返回值。



要解决这个问题,您可以:

1)制作myValue协议2的返回类型,以便Dukes和Silvers都返回protocol2类型。2)制作一个符合协议2的泛型数组。

/ p>

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:

Protocol 'MyProtocol1' can only be used as a generic constraint because it has Self or associated type requirements.

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

这篇关于自协议的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆