Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explit conformance to Codable removes memberwise initializer generation on structs

Tags:

swift

codable

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?

like image 602
Alex Bollbach Avatar asked Jan 08 '18 17:01

Alex Bollbach


People also ask

How do I add a custom initializer to a struct without losing its Memberwise initializer?

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.

What is a Memberwise initializer?

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 .

Does struct have init Swift?

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.


1 Answers

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")
like image 87
Palle Avatar answered Oct 19 '22 16:10

Palle