【问题标题】:Swift give let valuesSwift 赋予 let 值
【发布时间】:2018-10-18 17:11:51
【问题描述】:

我想写不要让价值观

我有

 "id": 17,
 "name": "",
    "team_id": 4,
    "is_delete": false,
    "created_at": "2018-04-30",
    "members": [
        {
            "id": 42,
            "username": "ie",
        }
    ],
    "description": null,

我尝试这样做

let id: Int
let name: String
let team_id: Int
let is_delete: Bool
let created_at: String

let description: NSNull

但不知道正确添加成员数组。并且 NSNull 对 null 值是正确的?

【问题讨论】:

  • 成员是字典
  • @Jake 不,这是一个字典数组。
  • 是的,我正在编辑它,你打败了我。应用程序比我的 Mac 慢。
  • 不清楚你在问什么。您是否正在尝试创建一个可以来回映射到 JSON 的结构?请澄清您的问题。

标签: arrays swift let


【解决方案1】:

所以我想您正在尝试编写可用于解码 JSON 的 Codable 结构/类?

处理null 的方式是使用可选类型。从名字来看,我猜description如果不为空的话应该是一个字符串,所以我们应该使用String?作为类型:

struct TeamMember: Codable {
    let id: Int
    let username: String
}

struct Team: Codable {
    let id: Int
    let name: String
    let team_id: Int
    let is_delete: Bool
    let created_at: String
    let members: [TeamMember]

    let description: String? // <---- this line
}

这里是一个解码的例子:

// I escaped the json using an online decoder I found. It's basically the same JSON in the question.
let jsonData = "{ \"id\": 17,\r\n \"name\": \"\",\r\n    \"team_id\": 4,\r\n    \"is_delete\": false,\r\n    \"created_at\": \"2018-04-30\",\r\n    \"members\": [\r\n        {\r\n            \"id\": 42,\r\n            \"username\": \"ie\",\r\n        }\r\n    ],\r\n    \"description\": null}".data(using: .utf8)
let decoder = JSONDecoder()
let team = try! decoder.decode(Team.self, from: jsonData!)
print(team.id)

【讨论】:

  • 刚来这里是为了建议结构。很好的答案!
猜你喜欢
  • 1970-01-01
  • 2016-12-10
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2017-03-08
相关资源
最近更新 更多