Easy struct initialization in Swift

Did you know that swift has automatic init generation for all of your properties? Let’s say you have amyStruct :

struct myStruct {
let myString: String?
let myInt: Int?
let myDouble: Double?
}

In a situation like this you don’t even need to write init It has been automatically generated for you!

Try instantiating it and will see autocomplete like that:

BOOM! You saved yourself 2 minutes of typing!

But there is a catch: you have to set all those 3 parameters with some values or nil

myStruct(myString: "Something", myInt: nil, myDouble: nil)

Does it work with classes? NO


Another thing you can do is to set your init argument as optional ! It requires the typing of the actual init method. After any parameter you simply add =nil☝️ and this parameter becomes optional!

struct myStructWithInit {
let myString: String?
let myInt: Int?
let myDouble: Double?

init(myString: String? = nil, //👈
myInt: Int? = nil,
myDouble: Double? = nil) {

self.myString = myString
self.myInt = myInt
self.myDouble = myDouble
}
}

Now when you instantiate this struct your autocomplete will have initializer with no parameters at all :

But it also means that you can instantiate it with only one or any optional parameters. It gives you freedom 😉

myStructWithInit(myString: "Something")
or
myStructWithInit(myString: "Something", myInt: 2)
or
myStructWithInit(myString: "Something", myInt: 2, myDouble: 3.0)

Add any parameters you want and delete the rest!!!

Like what you read? Give Serguei Vinnitskii a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.