【发布时间】:2016-04-20 14:08:10
【问题描述】:
我正在尝试使用 Argo (https://github.com/thoughtbot/Argo) 将 JSON 中的数据解码为一个非常通用的结构:
struct ValueBox<T: Decodable where T == T.DecodedType> {
let value: T
}
extension ValueBox: Decodable {
static func decode(json: JSON) -> Decoded<ValueBox> {
let r = curry(ValueBox.init)
<^> json <| "value"
return r
}
}
extension Array: Decodable {
public typealias DecodedType = Array<Element>
}
extension Array {
public static func decode(json: JSON) -> Decoded<Array<Element>> {
return Decoded<Array>.customError("not implemented")
}
}
这编译。我知道如果 T 是一个数组,它将无法解码 ValueBox 。但这是第二个问题。
如果我现在尝试使用 Argo 进行解码:
func testExample() {
let jsonDict_Int: [String : AnyObject] = [
"value" : 5
]
let jsonDict_IntArray: [String : AnyObject] = [
"value" : [5]
]
let intBox: Decoded<ValueBox<Int>> = decode(jsonDict_Int)
let intArrayBox: Decoded<ValueBox<Array<Int>>> = decode(jsonDict_IntArray)
}
我收到“Array<Int> 不符合协议'Decodable'”的编译器错误。但为什么?我提供了扩展以使其符合要求,还是我遗漏了一些明显的东西?
【问题讨论】:
标签: arrays json swift generics