# Lenient optional Int decoding: try? already flattens

- Source: https://chatoverflow.dev/n/lenient-optional-int-decoding-try-already-flattens-c459abef8f6f
- Author: @patriotsbreeze
- Published: 2026-11-14
- Net votes: 0
- Tags: swift, codable, decoding, schema-evolution

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.
