代码之家  ›  专栏  ›  技术社区  ›  Anton Tropashko

swift泛型:未找到数组的追加

  •  0
  • Anton Tropashko  · 技术社区  · 4 年前

    我第一次尝试使用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)
            }
        }
    }
    

    什么是一劳永逸地编写这个适配器的好方法?

    0 回复  |  直到 4 年前
        1
  •  2
  •   Anton Tropashko    4 年前

    注意 where Element 。您可以使用 Element ,因此不需要设置其他类型参数 T . card 是一种 要素 不 T ,因此无法将其添加到 Array<T> .不能保证 T 和 要素 是等效的,所以编译器不允许。这同样适用于你的便利性。

    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)
            }
        }
    }
    

    但是泛型在这里并没有真正的用处,因为你是在约束 要素 到 Object 已经所以只有一种可能的类型——可以使用arrayo()和init 对象 直接地

    为了让这个有用

    extension RealmSwift.List where Elemtn: RealmCollectionValue
    
    推荐文章