将结构数组分配给协议数组 [英] Assigning an array of structs to an array of protocols

查看:50
本文介绍了将结构数组分配给协议数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

protocol MyProtocol {
}

struct MyStruct: MyProtocol {
}

var s1 = MyStruct()
var s2 = MyStruct()
var s3 = MyStruct()

var structArray = [s1, s2, s3]

当我尝试将这个结构数组分配给一个协议数组时(structArray 中的每个结构都符合):

When I try to assign this array of structs to an array of protocols (that each struct in structArray conforms to):

var protocolArray:[MyProtocol] = structArray

我收到此错误:无法将类型[MyStruct]"的数组转换为指定类型[MyProtocol]"

我希望因为数组中的每个对象都符合协议,所以可以说符合某种协议的结构数组"可以分配给期望符合该协议的任何对象的数组"的东西协议".但是,如果类型是一个数组"而不是事物",这可能不适用,如果有任何意义的话.

I would expect that since each object in the array conforms to the protocol it would be ok to say that "an array of structs that conform to some protocol" is assignable to something that expects "an array of anything that conforms to that protocol". But maybe this doesn't apply when the type is "an array of " vs just "thing", if that makes any sense.

例如,这是有效的:

var p1:MyProtocol = s1

因为s1符合MyProtocol.但是如果你使用数组,那么它似乎不再成立.

Because s1 conforms to MyProtocol. But if you use arrays then it doesn't seem to hold anymore.

顺便说一句,这似乎也有效:

Incidentally, this seems to work too:

var p1Array:[MyProtocol] = [s1, s2, s3]

大概是因为数组的类型被确定为 [MyProtocol] 并且不是由某个先前的变量预先确定的(就像我上面的例子一样).

Presumably because the type of the array is determined to be [MyProtocol] and isn't predetermined by some previous variable (like in my example above).

所以无论如何,所有这一切都是为了问:解决这个问题的最佳方法是什么?如何将一个结构数组(符合某种协议)分配给另一个类型只是符合该协议的事物数组"的数组.

So anyways, all this to ask: What's the best way around this? How can I assign an array of structs (that conform to some protocol) to another array whose type is just "an array of things that conform that protocol".

我对 Swift 还很陌生,所以我可能会遗漏一些微不足道的东西.

I'm fairly new to Swift so I may be missing something trivial.

推荐答案

我通常只是将数组map 到我需要的类型:

I usually just map the array to the type I need:

var protocolArray: [MyProtocol] = structArray.map { $0 as MyProtocol }

当你这样做时,你实际上可以摆脱类型注释,这样整个表达式实际上就没有那么长了:

When you do that, you can actually get rid of the type annotation, so that the expression as a whole isn't actually that much longer:

var protocolArray = structArray.map { $0 as MyProtocol }

Swift 不会在数组类型之间自动转换,即使它们是兼容的.你必须以一种或另一种方式明确说明它.

Swift won't automatically convert between array types, even if they are compatible. You have to be explicit about it one way or another.

这篇关于将结构数组分配给协议数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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