標籤:blog http 使用 strong art html
為了初始化結構體和類等類型的執行個體屬性。
預設構造器
[html] view plaincopy
- struct Fahrenheit {
- var temperature: Doubleinit(){
- temperature = 32.0
- }
- }
var f = Fahrenheit() //調用預設構造器 init() ,沒有參數 沒有傳回值。
[html] view plaincopy
- 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