【问题标题】:Trying to decode arrays with Argo尝试使用 Argo 解码数组
【发布时间】: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&lt;Int&gt; 不符合协议'Decodable'”的编译器错误。但为什么?我提供了扩展以使其符合要求,还是我遗漏了一些明显的东西?

【问题讨论】:

    标签: arrays json swift generics


    【解决方案1】:

    对于第二个例子,我认为你必须使用&lt;^&gt; json &lt;|| "value" 而不是&lt;^&gt; json &lt;| "value"

    当你使用一个值数组时,你必须使用操作符

    a great link to the detailed Argo's documentation

    【讨论】:

    • 正如我所说,这是第 2 个问题。但这很困难,因为
    • 是的,但你不能这样做。你必须为数组做一些特别的事情。因为当您执行 ValueBox> 时,他尝试将 T 作为 Array 并且编译器希望 [T] 作为 Array.
    猜你喜欢
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    相关资源
    最近更新 更多