[英]Swift Protocols with Associated Type and Generics calling wrong function
[英]Swift generics & protocols: Return specialized type from static function?
我正在写一个从数据库获取对象的服务。 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")
}
}
您可以在协议定义中使用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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.