下面我粘贴了你应该能够粘贴到
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)
解决方法
append(_ newElement:Element)追加单个元素.
你想要的是追加(contentsOf newElements:C).
你想要的是追加(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]来整个阵列不得不施展每一个元素.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。