Swift给出值

时间:2018-05-08 17:05:01

标签: arrays swift let

我想写不要让值

我有

 "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是否为空值?

1 个答案:

答案 0 :(得分:2)

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

处理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)