Easy struct initialization in Swift

Serguei Vinnitskii
Jan 6, 2017 · 2 min read

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!!!

Serguei Vinnitskii

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade