加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – Swift 3无法将符合协议的对象数组附加到该协议的集合中

发布时间:2020-12-14 04:49:37 所属栏目:百科 来源:网络整理
导读:下面我粘贴了你应该能够粘贴到 Swift 3游乐场的代码并查看错误. 我定义了一个协议,并创建一个该类型的空数组.然后我有一个类符合我尝试附加到数组的协议,但我收到以下错误. protocol MyProtocol { var text: String { get }}class MyClass: MyProtocol { var
下面我粘贴了你应该能够粘贴到 Swift 3游乐场的代码并查看错误.

我定义了一个协议,并创建一个该类型的空数组.然后我有一个类符合我尝试附加到数组的协议,但我收到以下错误.

protocol MyProtocol {
    var text: String { get }
}

class MyClass: MyProtocol {
    var text = "Hello"
}
var collection = [MyProtocol]()
var myClassCollection = [MyClass(),MyClass()]
collection.append(myClassCollection)

argument type '[MyClass]' does not conform to expected type 'MyProtocol'

请注意,collection = myClassCollection返回以下错误:

error: cannot convert value of type '[MyProtocol]' to expected argument type 'inout _'

这在早期版本的Swift中有效.

到目前为止我找到的唯一解决方案是迭代并将每个元素添加到新数组中,如下所示:

for item in myClassCollection {
    collection.append(item)
}

任何帮助表示感谢,谢谢!

编辑

如下所示的解决方案是:

collection.append(contentsOf: myClassCollection as [MyProtocol])

当您缺少“as [MyProtocol]”时,真正的问题是误导性的编译器错误

编译器错误如下:

error: extraneous argument label 'contentsOf:' in call
collection.append(contentsOf: myClassCollection)

此错误导致用户从代码中删除contentsOf:然后导致我第一次提到的错误.

解决方法

append(_ newElement:Element)追加单个元素.
你想要的是追加(contentsOf newElements:C).

但是你有
将[MyClass]数组显式转换为[MyProtocol]:

collection.append(contentsOf: myClassCollection as [MyProtocol])
// or:
collection += myClassCollection as [MyProtocol]

正如Type conversion when using protocol in Swift中所解释的那样
将每个数组元素包装成一个包含“符合MyProtocol”的框,它不仅仅是一个重新解释
数组.

编译器会自动为单个值执行此操作(这就是原因

for item in myClassCollection {
    collection.append(item)
}

编译)但不是数组.在早期的Swift版本中,你你甚至不能用[MyProtocol]来整个阵列不得不施展每一个元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读