[英]Assign value to a two-dimensional array in swift
我有一段代碼如下:
protocol SomeProtocol {
}
struct SomeObject: SomeProtocol {
}
struct Test {
var arr: [[SomeProtocol]]
mutating func testFunction(objs:[[SomeObject]]) {
self.arr = objs
}
}
如您所見, SomeObject
確認了協議,但編譯器向我顯示了一個
error " cannot assign value of type '[[SomeObject]]' to type '[[SomeProtocol]]'".
有人可以告訴我原因嗎?
非常感謝!
因為[[SomeObject]]
與[[SomeProtocol]]
- 請參閱上面的@ TeeJay的評論。 如何解決這樣的問題:
protocol SomeProtocol {
}
struct SomeObject: SomeProtocol {
}
struct Test {
var arr: [[SomeProtocol]]
mutating func testFunction(objs:[[SomeObject]]) {
self.arr = []
for a in objs {
var innerArray = [SomeProtocol]()
for e in a {
innerArray.append(e)
}
self.arr.append(innerArray)
}
}
}
或者,正如@MartinR指出的那樣,你可以使用map
。
如果我嘗試用內部回路短路
self.arr = []
for a in objs {
self.arr.append(a)
}
我得到錯誤“無法將類型'Array <SomeObject>'的值轉換為預期的參數類型[SomeProtocol]”,這在一個層面上是完全正確的 - 它們不相同 - 它是元素,而不是集合,符合協議。 除非您明確地執行此操作,否則數組賦值不會深入到協議一致性的最終元素類型。
這並不奇怪 - 您不希望以下工作:
struct SomeOther1 {
var a : SomeProtocol
}
struct SomeOther2 {
var a : SomeObject
}
let x = SomeOther2(a: SomeObject())
let y: SomeOther1 = x // ERROR
雖然這應該(並且確實)有效:
let x = SomeOther2(a: SomeObject())
let y = SomeOther1(a: x.a)
由於Arrays是使用泛型的Struct
,我們可以嘗試使用泛型:
struct SomeOther<T> {
var a: T
}
let z = SomeOther<SomeObject>(a: SomeObject()) // OK, of course
let w = SomeOther<SomeProtocol>(a: SomeObject()) // OK, as expected
let v: SomeOther<SomeProtocol> = z // Doesn't work - types are not the same.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.