爲了初始化結構體和類等類型的實例屬性。html
默認構造器spa
[html] view plaincopy.net
struct Fahrenheit { orm
var temperature: Doubleinit(){ htm
temperature = 32.0 對象
} blog
} get
var f = Fahrenheit() //調用默認構造器 init() ,沒有參數 沒有返回值。it
[html] view plaincopyio
println("The default temperature is \(f.temperature)°Fahrenheit")
// prints "The default temperature is 32.0° Fahrenheit"
自定義構造器
定義類兩個構造器:init(fromFahrenheit:) 和init(fromKelvin:)
[html] view plaincopy
struct Celsius {
var temperatureInCelsius: Double = 0.0
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0)
/ 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin -273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit:212.0)
// boilingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater =Celsius(fromKelvin:273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
析構器(Deinitializer)
析構器與構造器相反,在對象釋放時候調用。 使用關鍵字 deinit,語法以下:
[html] view plaincopy
deinit {
// perform thedeinitialization
}
實例:
[html] view plaincopy
class Player {
var coinsInPurse:Int init(coins: Int) {
println("call init")
coinsInPurse= coins
}
func winCoins(coins: Int) {
coinsInPurse+= 10
}
deinit {
coinsInPurse = 0
}
}
var playerOne: Player? = Player(coins: 100)
println("coinsInPurse : \(playerOne!.coinsInPurse)
coins")
playerOne = nil
println("PlayerOne has leftthe game")
Swift交流討論論壇論壇:http://www.cocoagame.net
歡迎加入Swift技術交流羣:362298485