Swift Introduction | Class Basics | Initializers
Until now, instances have been created without arguments, as in Helo(). It is convenient to pass required values when creating an instance.
Use an initializer for this purpose. An initializer is a special method that runs automatically when an instance is created. Define it as follows.
init(arguments) {
...... initialization process ......
}
Do not write func init. Write only init. An initializer is a special method and does not require func.
Declare arguments inside the parentheses to pass values when creating an instance. The following is a simple example.
import Cocoa
class Helo {
var name:String;
init(name:String){
self.name = name;
}
func say(){
print("Hello, " + name + "!");
}
}
var obj:Helo = Helo(name:"Taro");
obj.say();
The Helo class defines an initializer in the form init(name:String). Create an instance by passing an argument, as in Helo(name:"Taro").
Inside the initializer, self.name assigns the argument name to the name property of the Helo class. The special value self represents the instance itself. This syntax refers to the name property of the current instance and is frequently used in class definitions.