我第一次嘗試使用 swift 泛型:
extension RealmSwift.List where Element == Object {
// @deprecated use RealmSwift.List<>
func arrayo<T: Object>() -> [T] {
var res: [T] = []
for card in self {
res.append(card) <- here I got
呼叫實體方法“附加”時沒有完全匹配
}
return res
}
convenience init<T: Object>(objects: [T]) {
self.init()
for card in objects {
append(card)
}
}
}
一勞永逸地撰寫這個配接器的好方法是什么?
uj5u.com熱心網友回復:
注意where Element. 您可以參考使用的串列項的型別Element,因此您無需設定其他型別引數T。card是Elementnot型別T,因此您不能將其添加到Array<T>. 不能保證TandElement是等價的,所以編譯器不允許這樣做。這同樣適用于您的便利 init。
extension RealmSwift.List where Element == Object {
// @deprecated use RealmSwift.List<>
func arrayo() -> [Element] {
var res: [Element] = []
for card in self {
res.append(card) // Now you are adding an `Element` to the array of `Element` so it will work.
}
return res
}
convenience init(objects: [Element]) {
self.init()
for card in objects {
append(card)
}
}
}
但是泛型在這里并不是很有用,因為你已經限制Element了Object。所以只有一種可能的型別 - 你可以讓 arrayo() 和 initObject直接使用。
為了使這個有用做
extension RealmSwift.List where Elemtn: RealmCollectionValue
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460201.html
