我無法解決這個問題。我有下面的代碼。我的問題是。為什么我無法在函式 compareId 中訪問 id (我得到的錯誤是“型別‘T.ItemType’的值沒有成員‘id’”),但在函式 compareIdW 中我可以訪問 id?任何人都可以向我解釋這一點嗎?我會感謝每一個幫助。謝謝
import Foundation
protocol ProtoA: Identifiable{
var id: UUID { get }
}
protocol ProtoB: Identifiable{
associatedtype ItemType = ProtoA
var id: UUID { get }
var arrayOfItems: [ItemType] { get }
}
class M<T:ProtoB>{
var itemA: T.ItemType?
init(itemA: T.ItemType?) {
self.itemA = itemA
}
// This does not work
func compareId(of item: T.ItemType) -> Bool {
return item.id == self.itemA?.id // when
}
// But this does
func compareIdW<U: ProtoA>(of item: U) -> Bool where U == T.ItemType {
return item.id == self.itemA?.id
}
}
uj5u.com熱心網友回復:
那是因為T.ItemType曖昧。
在編譯器是看你的表情一點都真的知道的是,T.ItemType是associatedType。它并不真正知道分配給特定實體的屬性ItemType可能具有哪些。
考慮這個代碼:
struct Marshmallow {
}
struct SmoresStruct : ProtoB {
typealias ItemType = Marshmallow
var id: UUID = UUID()
var arrayOfItems: [Self.ItemType] = Array<Marshmallow>()
}
class SmoresClass : M<SmoresStruct> {
}
SmoresStruct是struct滿足它實作的約束的 ,它ProtoB可用于創建SmoresClass(的子類class M),因為它滿足您對 的泛型引數施加的所有約束class M。但是ItemType, Marshmallow,在您試圖暗示應該具有屬性Identifiable的實作中并非如此,這是它沒有的一個實體。class MT.ItemTypeid
您需要對M類的宣告進行額外的約束:
class M<T : ProtoB> where T.ItemType : Identifiable {
...
}
現在,如果您嘗試使用Marshmallowas ,ItemType您將獲得:
型別“SmoresStruct.ItemType”(又名“棉花糖”)不符合“可識別”協議
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334464.html
