Swift 给 let 值

Swift give let values

我想写不要让值

我有

 "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 对空值是否正确?

所以我想你正在尝试编写一个 Codable struct/class 来解码你的 JSON?

处理null的方法是使用可选类型。从名称来看,我猜 description 如果它不为 null 应该是一个字符串,所以我们应该使用 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)