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

Swift Initialization Struct

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).

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
}

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 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 — entirely for free.

← Home