为了初始化结构体和类等类型的实例属性。
默认构造器
struct Fahrenheit { var temperature: Doubleinit(){ temperature = 32.0 } }
var f = Fahrenheit() //调用默认构造器 init() ,没有参数 没有返回值。
println("The default temperature is \(f.temperature)°Fahrenheit") // prints "The default temperature is 32.0° Fahrenheit"
自定义构造器
定义类两个构造器:init(fromFahrenheit:) 和init(fromKelvin:)
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,语法如下:
deinit { // perform thedeinitialization }
实例:
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