0

我有一个符合 Decodable 的结构。它有 50 个字符串属性和只有一个布尔值。该布尔值来自服务器,如字符串“false”/“true”或有时如整数 0/1,因此无法从框中解码。我怎样才能让它解码但不编写大量手动解码所有 50 个字符串属性?也许以某种方式覆盖 decodeIfPresent for Bool,但我无法使其工作。我如何避免通过手动解码所有内容和所有这些东西来避免创建 init 并且只处理那个 Bool?如果可能,没有计算属性。

struct Response: Decodable {
    var s1: String
    var s2: String
    var s3: String
    //...........
    var s50: String
    var b1: Bool
    var b2: Bool
}

这是json示例:

{
    "s1":"string"
    "s2":"string"
    "s3":"string"
    //..........
    "s50":"string"
    "b1":"true"
    "b2":"0"
}

试过这个但不起作用(((

extension KeyedDecodingContainer { //Doesn't work, no execution
    func decodeIfPresent(_ type: Bool.Type, forKey key: K) throws -> Bool {
        return try! self.decodeIfPresent(Bool.self, forKey: key)
    }
    func decodeIfPresent(_ type: Bool.Type, forKey key: K) throws -> Bool? {
        return try? self.decodeIfPresent(Bool.self, forKey: key)
    }
}
4

1 回答 1

5

解决此问题的一种方法是编写一个处理自定义解码的属性包装器,如下所示:

@propertyWrapper
struct FunnyBool: Decodable {
    var wrappedValue: Bool

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        if let value = try? container.decode(Bool.self) {
            wrappedValue = value
        }
        else if
            let string = try? container.decode(String.self),
            let value = Bool(string)
        {
            wrappedValue = value
        }
        else if
            let int = try? container.decode(Int.self),
            let value = int == 0 ? false : int == 1 ? true : nil
        {
            wrappedValue = value
        }
        else {
            // Default...
            wrappedValue = false
        }
    }
}

像这样使用它:

struct Response: Decodable {
    var s1: String
    var s2: String
    @FunnyBool var b: Bool
}

let json = #"{ "s1": "hello", "s2": "world", "b": 1 }"#
let response = try! JSONDecoder().decode(Response.self, from: json.data(using: .utf8)!)
dump(response)

游乐场输出:

▿ __lldb_expr_11.Response
  - s1: "hello"
  - s2: "world"
  ▿ _b: __lldb_expr_11.FunnyBool
    - wrappedValue: true
于 2021-01-31T17:20:50.403 回答