Given:
struct Foo {
let bar: Bar
}
I get a convenience initializer to use:
let foo = Foo(bar: Bar())
But if Bar
isn't itself Codable
, or for some other reason I need to explicitly implement Codable
on Foo
then the convenience memberwise initializer is no longer present:
struct Foo: Codable {
init(from decoder: Decoder) throws {
}
func encode(to encoder: Encoder) throws {
}
let bar: Bar
}
and i get:
let foo = Foo(bar: Bar())
Incorrect argument label in call (have 'bar:', expected 'from:')
Is it possible to have the best of both worlds here?
If you want to keep both the default initializer and your own custom ones, there's a simple trick: create your initializers inside an extension rather than as part of the main struct definition.
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name. The example below defines a structure called Size with two properties called width and height .
In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self.
You can implement the Codable
conformance in an extension.
When adding any struct initializer in an extension, the memberwise initializer will not be removed.
struct MyStruct {
var name: String
}
extension MyStruct: Codable {} // preserves memberwise initializer
MyStruct(name: "Tim")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With