Swift Decodable Optional Key

前端 未结 3 2124

(This is a follow-up from this question: Using Decodable protocol with multiples keys.)

I have the following Swift code:

let additionalInfo          


        
3条回答
  •  执念已碎
    2020-12-09 11:13

    I had this issue and I found this solution, just in case is helpful to somebody else:

    let ageContainer = try? values.nestedContainer(keyedBy: AgeKeys.self, forKey: .age)
    self.age = try ageContainer?.decodeIfPresent(Int.self, forKey: .realAge)
    

    If you have an optional container, using try? values.nestedContainer(keyedBy:forKey) you don't need to check if the container exist using contains(.

提交回复
热议问题