How to manually decode Optional value

struct Ball: Codable {}

struct Ground: Codable {
    var ball: Ball?
    init() { ball = nil }
    enum CodingKeys: String, CodingKey { case ball }
    public init(from decoder: Decoder) throws {
        self.init()
        let values = try decoder.container(keyedBy: CodingKeys.self)
        ball = try values.decode(Ball?.self, forKey: .ball)
    }
}

In code above in run time I get the error like this:
keyNotFound(CodingKeys(stringValue: "ball", intValue: nil)
How to write initialization from Decoder correct with optional properties?

Use decodeIfPresent(_:forKey:).

4 Likes