【问题标题】:How to include enum in Swift 4 JSON decoding? [duplicate]如何在 Swift 4 JSON 解码中包含枚举? [复制]
【发布时间】:2017-10-04 18:16:00
【问题描述】:

从后端接收消息,现在我想使用 swift 4 JSON 解码。我使用具有常规属性(String、Int、...)的对象对其进行了测试,并且工作没有问题。现在我想处理具有枚举属性的对象,我想在对象初始化时设置该属性。如何设置初始化,使其包括设置枚举?

struct WebPacket: Decodable {
  let type: MessageType
  let message: String

  init(with type: MessageType, data: Data) {
    type = type
    // fill others
  }
}

enum MessageType: String {
  case unknown
  case getDescription     = "get-daa-description"
  case description        = "daa-description"
  case holdings           = "holdings"
}

【问题讨论】:

  • 对不起,我修好了。这个初始化函数只是我想要实现的即兴创作。

标签: ios swift enums swift4


【解决方案1】:

这很容易。由于MessageType 得到了一个符合 JSON 的原始值,所以只需采用 Decodable

enum MessageType: String, Decodable {
    case unknown
    case getDescription     = "get-daa-description"
    case description        = "daa-description"
    case holdings           = "holdings"
}

struct WebPacket : Decodable {
    let type : MessageType
    let message : String
}

let jsonString = "{\"type\": \"daa-description\", \"message\" : \"Hello World\"}"

let jsonData = Data(jsonString.utf8)

do {
    let decoded = try JSONDecoder().decode(WebPacket.self, from: jsonData)
    print("decoded:", decoded)
} catch {
    print(error)
}

【讨论】:

  • jsonString.data(using: .utf8)! 可以简化,无需强制解包(在这种情况下这不是问题,因为它永远不会崩溃)到Data(jsonString.utf8)
  • @LeoDabus 哇,这真的很酷,谢谢。
  • 不客气。这只有在 Swift 3 之后才有可能,因为 Data 符合集合
【解决方案2】:

请检查:

struct WebPacket: Decodable {
    var type: MessageType

    init(with type: MessageType, data: Data) {
        self.type = type
    }
}

enum MessageType: String, Decodable { // Here I just added Decodable
    case unknown
    case getDescription     = "get-daa-description"
    case description        = "daa-description"
    case holdings           = "holdings"
}

let json = """
    [
        {
            "type": "get-daa-description"
        },    
        {
            "type": "daa-description"
        },
        {
            "type": "holdings"
        }
    ]
"""

do {
    let webPacket = try JSONDecoder().decode([WebPacket].self, from: json.data(using: .utf8)!)
    for i in 0..<webPacket.count {
        print(webPacket[i].type.rawValue)
    }
} catch {
    print(error)
}

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2023-03-04
    • 2019-01-06
    • 1970-01-01
    • 2014-12-13
    • 2018-01-25
    相关资源
    最近更新 更多