Swift泛型和协议:从静态函数返回专用类型?

时间:2019-08-07 17:08:59

标签: ios swift generics swift-protocols

我正在编写一项从数据库获取对象的服务。 Swift中所有这些实体都遵循协议DAO,以使get函数可重用。我想在协议中添加一个方法,该方法可以接受字典并返回对象类型。

是否可以编写返回专用类类型的静态协议方法?

下面的代码(大致)说明了我正在尝试做的事情。

protocol DAO {
    static func fromDictionary(_ dictionary: [String : Any]) -> T // ??
}

class User : DAO {

    init(_ dictionary: [String : Any]) {
        ...
    }


    static func fromDictionary(_ dictionary: [String : Any]) -> User {
        return User(dictionary)
    }
}

class DataService<T> where T: DAO {

    func get(id: String) -> T {
        let dictionary = API.get(id)
        return T.fromDictionary(dictionary)
    }
}

class ViewController : UIViewController {

    let dataService: DataService<User>
    let user: User

    override func viewDidLoad() {
        super.viewDidLoad()
        dataService = DataService<User>()
        user = dataService.get(id: "abcdefg")
    }

}

1 个答案:

答案 0 :(得分:2)

您可以在协议定义中使用AssociatedTypes

protocol DAO {
    associatedtype Item
    static func fromDictionary(_ dictionary: [String : Any]) -> Item
}

class User : DAO {

    static func fromDictionary(_ dictionary: [String : Any]) -> User {
         return User(dictionary)
    }
}

Read the official docs for AssociatedTypes

相关问题