Init() in Swift.

John Xavier
The Startup
Published in
1 min readAug 26, 2020

Init() is a method used to initialize values in swift. Swift will not allow you to compile a class without initializing the non-optional values of a class.

To avoid this error you could initialize above variables with some default value when we create them, like below.

var myStringValue : String = “Hello”
var myIntValues : Int = 0

But what if you don’t want to assign values to the variables while creating them, you could always make them optional. But creating unwanted optionals are not the right approach, that's where we use Init() method. It can be used to initialize the values of class when creating the object of the class.

class initExample{var myStringValue : Stringvar myIntValue : Intinit(myString:String, myInt:Int) {self.myStringValue = myStringself.myIntValue = myInt}}let initObject = initExample(myString: “Hello”, myInt: 10)

This is a basic feature of swift, that is used by developers all the time. Hope I helped.

--

--