Swift Codable null handling

后端 未结 2 1034
一生所求
一生所求 2021-02-05 14:46

I have a struct that parse JSON using Codable.

struct Student: Codable {
    let name: String?
    let amount: Double?
    let adress: String?
}
         


        
2条回答
  •  既然无缘
    2021-02-05 14:52

    Let me do this Playground for you since an example shows you more than a hundred words:

    import Cocoa
    
    struct Student: Codable {
        let name: String?
        let amount: Double?
        let adress: String?
    }
    
    let okData = """
    {
       "name": "here",
     "amount": 100.0,
     "adress": "woodpecker avenue 1"
    }
    """.data(using: .utf8)!
    
    let decoder = JSONDecoder()
    let okStudent = try decoder.decode(Student.self, from:okData)
    print(okStudent)
    
    let nullData = """
    {
       "name": "there",
     "amount": null,
    "adress": "grassland 2"
    }
    """.data(using: .utf8)!
    
    let nullStudent = try decoder.decode(Student.self, from:nullData)
    print(nullStudent)
    

    null is handled just fine if you define your structs using optionals. I would however advise against it if you can avoid it. Swift provides the best support I know to help me not forgetting to handle nil cases wherever they may occur, but they are still a pain in the ass.

提交回复
热议问题