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