How to preserve a struct memberwise initializer when you have a custom initializer

⋅ 1 min read ⋅ Swift Initialization Struct

Table of Contents

In the previous article, I talk about Memberwise Initializers, which you get for free on structure types if you don't define any custom initializers.

There might be a time where you want to have a custom initializer, but you don't want to lose memberwise initializer.

Extension

To preserve a memberwise initializer, you can declare a custom initializer in an extension.

struct User {
let firstName: String
let lastName: String
}

extension User {
init(fullName: String) {
let components = fullName.components(separatedBy: " ")
firstName = components[0]
lastName = components[1]
}
}

The above User struct will got two initializers, User(firstName: String, lastName: String) and User(fullName: String).

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Explicit conformance

Another use case is when you have explicit conformance to Codable protocol.

struct User: Codable {
let firstName: String
let lastName: String

init(from decoder: Decoder) throws {
...
}
}

The above code will remove a memberwise initializer since you declare a custom initializer. You can conform to Codable protocol in an extension and declare a custom initializer there to preserve a memberwise initializer.

struct User {
let firstName: String
let lastName: String
}

extension User: Codable {
init(from decoder: Decoder) throws {
...
}
}

If you don't need special care in init(from decoder: Decoder) throws, you can conform to it normally and get both memberwise initializer, and the one generated from Codable.

struct User: Codable {
let firstName: String
let lastName: String
}

You can easily support sarunw.com by checking out this sponsor.

Sponsor sarunw.com and reach thousands of iOS developers.

Read more article about Swift, Initialization, Struct, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Memberwise Initializers for Structure Types

Struct is one of the basic building blocks in your app. Today I'm going to share some tips about memberwise Initializers.

Next
History of Auto Layout constraints

Learn different ways to define Auto Layout constraints programmatically.

← Home