【发布时间】:2021-10-20 20:59:46
【问题描述】:
我无法解决这个问题。我有下面的代码。我的问题是。为什么我无法在函数 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
}
}
【问题讨论】:
标签: swift generics swift-protocols