Explit conformance to Codable removes memberwise initializer generation on structs

▼魔方 西西 提交于 2019-12-10 13:19:55

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!