My first attempt to use swift generics:
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
No exact matches in call to instance method 'append'
}
return res
}
convenience init<T: Object>(objects: [T]) {
self.init()
for card in objects {
append(card)
}
}
}
what's a good way to write this adapter once and for all?
Notice the
where Element
. You can refer to the type of the list items usingElement
, so you do not need to set up another type parameterT
.card
is of typeElement
notT
, so you cannot add it to theArray<T>
. There is no guarantee thatT
andElement
are equivalent so the compiler doesn't allow it. The same applies for your convenience init.But generics are not really useful here because you are constraining
Element
toObject
already. So there is only one potential type - You could make arrayo() and the init useObject
directly.To make this useful do