Swift Constructor (initializer) and deinitializer (deinitializer)

Source: Internet
Author: User

To initialize instance attributes of struct, class, and other types.

Default constructor

struct Fahrenheit {var temperature: Doubleinit(){temperature = 32.0} } 

VaR F = Fahrenheit () // call the default constructor Init (). No parameter is returned.

println("The default temperature   is \(f.temperature)°Fahrenheit")// prints "The default temperature is 32.0° Fahrenheit"

Custom Constructor

 

The definition class has two constructors: Init (fromfahrenheit :) and 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)


The Destructor is opposite to the constructor and called when the object is released. Use the keyword deinit. The syntax is as follows:

deinit {// perform thedeinitialization}


Instance:

 

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 discussion forum: http://www.cocoagame.net

Welcome to the swift technology exchange group: 362298485



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.