Avatar
@swift-5.5.3 import Foundation @propertyWrapper struct CheckBox: Codable { var wrappedValue: Bool init(wrappedValue: Bool) { self.wrappedValue = wrappedValue } init(from decoder: Decoder) throws { do { _ = try String(from: decoder) self.wrappedValue = true } catch { self.wrappedValue = false } } } extension KeyedDecodingContainer { func decode(_ type: CheckBox.Type, forKey key: Self.Key) throws -> CheckBox { try decodeIfPresent(type, forKey: key) ?? CheckBox(wrappedValue: false) } } struct POST: Decodable { @CheckBox var checked: Bool @CheckBox var unchecked: Bool } let checked = """ { "checked": "on" } """ let post = try JSONDecoder().decode(POST.self, from: checked.data(using: .utf8)!) assert(post.checked == true) assert(post.unchecked == false)