Swift 泛型和协议:Return 来自静态函数的特殊类型?

Swift generics & protocols: Return specialized type from static function?

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

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

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

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

}

您可以在协议定义中使用 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