问题
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?
回答1:
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")
来源:https://stackoverflow.com/questions/48155118/explit-conformance-to-codable-removes-memberwise-initializer-generation-on-struc