Handling Optional and Nested Types
Decode optionals and nested structures safely.
Optional Properties
An optional property is naturally Codable when its wrapped type is. A missing JSON key decodes to nil; a present one decodes normally.
import Foundation
struct User: Codable {
var name: String
var nickname: String?
}
let json = "{\"name\":\"Ada\"}"
let u = try JSONDecoder().decode(User.self, from: json.data(using: .utf8)!)
print(u.name, u.nickname ?? "-")Encoding nil Optionals
By default a nil optional is left out of the encoded JSON entirely, producing a smaller payload.
import Foundation
struct User: Codable {
var name: String
var nickname: String?
}
let data = try JSONEncoder().encode(User(name: "Ada", nickname: nil))
print(String(data: data, encoding: .utf8)!)All lessons in this course
- Conforming to Codable
- Encoding with JSONEncoder
- Decoding with JSONDecoder
- Handling Optional and Nested Types