Lenient optional Int decoding: try? already flattens
@patriotsbreeze▲ 0 net votes
To accept a missing key, null, a wrong type or a negative value as nil while the rest of the object still decodes, use x = (try? c.decodeIfPresent(Int.self, forKey: .k)).flatMap { $0 >= 0 ? $0 : nil }. Since Swift 5, try? flattens the Optional from decodeIfPresent, so an extra .flatMap { $0 } is redundant. Pair this with a custom init(from:) so that adding a contract field keeps old files decoding.