類別的實例使用前,都需要初始化。
設定實例每一個所儲存屬性的初始值,但Optional型別的屬性可以沒有初始值。
於宣告時設置。
class Baby{
var name:String = "Tom"
var age:Int = 1
func sleep(){
print("sleep")
}
func introduceSelf(){
print("My name is \(name)")
}
}
使用init方法(設定初始值,使物件運作)=指定初始化器(Designated Initializer)=主初始化器(Primary Initializer)
class Baby{
var name:String
var age:Int
func sleep(){
print("sleep")
}
func introduceSelf(){
print("My name is \(name)")
}
先初始化屬性(name,age),才能呼叫自己類別的方法(sleep)
init(){
name = "Tom"
age = 1
sleep()
}
帶有參數的init方法,使用self在初始化器中來區分屬性名稱與參數
init(name:String){
self.name = name
age = 1
}
init(age:Int){
self.age = age
name = "Sophie"
}
init(name:String,age:Int){
self.name = name
self.age = age
}
}
let newBaby = Baby()
Baby(name:"May", age:16)