[英]Swift 3 unable to append array of objects, which conform to a protocol, to a collection of that protocol
下面我粘貼了你應該能夠粘貼到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)
追加單個元素。 你想要的是append(contentsOf newElements: C)
。
但是你必須明確地將 [MyClass]
數組轉換為[MyProtocol]
:
collection.append(contentsOf: myClassCollection as [MyProtocol])
// or:
collection += myClassCollection as [MyProtocol]
正如在Swift中使用協議時的類型轉換中所解釋的那樣,這將每個數組元素包裝成一個包含“符合MyProtocol
東西”的框,它不僅僅是對數組的重新解釋。
編譯器會自動為單個值執行此操作(這就是原因
for item in myClassCollection {
collection.append(item)
}
編譯)但不是數組。 在早期的Swift版本中,您甚至無法使用as [MyProtocol]
整個數組,您必須轉換每個單獨的元素。
當集合只期望單個項目時,您嘗試附加數組。 例如,將集合更改為此編譯:
var collection = [[MyProtocol]]()
這里有一種方法可以將兩個數組加在一起:
func merge<T: MyProtocol>(items: inout [T], with otherItems: inout [T]) -> [T] {
return items + otherItems
}
var myClassCollection = [MyClass(), MyClass()]
var myClassCollection2 = [MyClass(), MyClass()]
let combinedArray = merge(items: &myClassCollection, with: &myClassCollection2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.