【问题标题】:Swift generics & protocols: Return specialized type from static function?Swift 泛型和协议:从静态函数返回专用类型?
【发布时间】:2019-08-07 17:08:59
【问题描述】:

我正在编写一个从数据库中获取对象的服务。 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")
    }

}

【问题讨论】:

  • 可以将返回类型设为Self

标签: ios swift generics swift-protocols


【解决方案1】:

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

【讨论】:

  • 看起来这个解决方案与上面的第一条评论一起工作,associatedType Item = Self
猜你喜欢
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
相关资源
最近更新 更多