Skip to content

Instantly share code, notes, and snippets.

@lnfnunes
Last active May 14, 2021 04:33
Show Gist options
  • Save lnfnunes/4560021e07615bd562aaff8a30c30994 to your computer and use it in GitHub Desktop.
Save lnfnunes/4560021e07615bd562aaff8a30c30994 to your computer and use it in GitHub Desktop.
Codable struct containing default values.
/// This enabled the struct to:
/// - Be auto-decodable via json.
/// - Assign a default value if the property is not present in json.
/// - Assign values via init constructor.
struct MyStruct: Codable, Equatable {
let propFoo: Bool
let propBar: Bool
// Set default values for missing properties
// {"propFoo": true, "propBar": true} // propBar => true
// {"propFoo": true} // propBar => false
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
propFoo = try container.decodeIfPresent(Bool.self, forKey: .propFoo) ?? false
propBar = try container.decodeIfPresent(Bar.self, forKey: .propBar) ?? false
}
// Set custom values via manual constructor
// MyStruct(propFoo: true, propBar: true)
init(propFoo: Bool, propBar: Bool) {
self.propFoo = propFoo
self.propFoo = propFoo
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment