【发布时间】:2016-04-28 17:08:32
【问题描述】:
我正在使用 Thoughtbot 的 Argo 框架将 JSON 对象解析为模型。
我遇到了一个问题,我有这样的协议及其扩展
protocol SomeProtocol {
associatedtype Model
func foo()
}
extension SomeProtocol where Model: Decodable {
func foo() -> Model? {
// someJSON is AnyObject in this case, say, from a network call
guard let model: Model = decode(someJSON) else { return nil }
return model
}
}
并且符合这个协议的类看起来像这样
class SomeClass: SomeProtocol {
typealias Model = ArgoModel
func bar() {
print(foo())
}
}
还有这样的模型
struct ArgoModel {
let id: String
}
extension ArgoModel: Decodable {
static func decode(j: AnyObject) -> Decoded<ArgoModel> {
return curry(self.init)
<^> j <| "id"
}
}
(我也在使用他们的 Curry 库来 curry init 方法)
我遇到的问题是,在 SomeProtocol 扩展中,关联类型 Model 无法被 Argo 解码。我得到的错误是
No 'decode' candidates produced the expected contextual result type 'Self.Model?'
这是 Swift 类型系统的限制吗?还是我缺少什么?
【问题讨论】:
标签: ios swift generics protocols