Customizing initialization
We want to initialize instances of the Circle
class with the radius value. In order to do so, we can take advantage of customized initializers. Initializers aren't methods, but we will write them with syntax that is very similar to the instance methods. They will use the init
keyword to differentiate from instance methods, and Swift will execute them automatically when we create an instance of a given type. Swift runs the code within the initializer before any other code within a class.
We can define an initializer that receives the radius value as an argument and use it to initialize a property with the same name. We can define as many initializers as we want to, and therefore, we can provide many different ways of initializing a class. In this case, we just need one initializer.
The following lines create a Circle
class and define an initializer within the class body. The code file for the sample is included in the swift_3_oop_chapter_02_02
folder:
class Circle...