Swift Generic:未找到数组的附加
我第一次尝试使用 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
调用实例方法“append”时没有完全匹配
}
return res
}
convenience init<T: Object>(objects: [T]) {
self.init()
for card in objects {
append(card)
}
}
}
一劳永逸地编写此适配器的好方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注意
where 元素
。您可以使用Element
引用列表项的类型,因此不需要设置另一个类型参数T
。card
的类型为Element
而不是T
,因此您无法将其添加到Array
中。无法保证T
和Element
等效,因此编译器不允许这样做。这同样适用于您的方便 init。但泛型在这里并没有多大用处,因为您已经将
Element
限制为Object
。因此只有一种潜在类型 - 您可以使 arrayo() 和 init 直接使用Object
。为了使这个有用做
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