Swift構造器(Initializer)與析構器(Deinitializer)

來源:互聯網
上載者:User

為了初始化結構體和類等類型的執行個體屬性。

預設構造器

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 = nilprintln("PlayerOne has leftthe game")


Swift交流討論論壇論壇:http://www.cocoagame.net

歡迎加入Swift技術交流群:362298485



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.