使用协议初始化程序

时间:2017-12-21 14:52:18

标签: ios swift generics initialization realm

我有这个方法,我想使用协议初始化程序初始化一个新的Realm对象(参见for-loop else closure),但由于某种原因它无法被识别。我能够使用默认初始化程序初始化对象,然后更新内容。可以这样做吗?

协议:

protocol UnequallyPersistable: class {

    var uniqueID: String { get set }
    var isDeleted: Bool { get set }

    init(withData data: NSDictionary)
    func update(withData data: NSDictionary)

}

工作,但不是最佳:

fileprivate func update<Element: UnequallyPersistable>(withData data: Any?, type: Element.Type) where Element: Object {
    let realm = try! Realm()
    realm.beginWrite()

    guard let items = data as? [NSDictionary] else {
        return
    }

    for itemData in items {
        guard let uniqueID = itemData["id"] as? String else {
            continue
        }
        let object = realm.object(ofType: type.self, forPrimaryKey: uniqueID)
        if let _object = object {
            _object.update(withData: itemData)
        } else {
            let newObject = type.init()
            newObject.update(withData: itemData)
            realm.add(newObject)
        }
    }

    try? realm.commitWrite()
}

不起作用:

fileprivate func update<Element: UnequallyPersistable>(withData data: Any?, type: Element.Type) where Element: Object {
    let realm = try! Realm()
    realm.beginWrite()

    guard let items = data as? [NSDictionary] else {
        return
    }

    for itemData in items {
        guard let uniqueID = itemData["id"] as? String else {
            continue
        }
        let object = realm.object(ofType: type.self, forPrimaryKey: uniqueID)
        if let _object = object {
            _object.update(withData: itemData)
        } else {
            let newObject = type.init(withData: itemData)
            realm.add(newObject)
        }
    }

    try? realm.commitWrite()
}

0 个答案:

没有答案