Home » Swift » Swift constructor (Initializer) & destructor

Swift constructor (Initializer) & destructor

// constructor (Initializer) 
// in order to initialize the instance properties of structures and classes,
// default constructor
struct Fash {
var temperature: Double
Init () {
Temperature = 32.0
}
}
var f = Fash () // calls the default constructor init (), with no arguments, no return value,
//var FF = Fash (temperature: 12)) / / if you do not write the default constructor, it can be invoked to specify parameters
print (, default constructor - (F.Temperature) )

// custom constructor 
struct Cele {
var, temp:, Double = 0.0
// distinguishes different constructors by name
Init (fromF, f:, Double) {
Temp = (F - 32.0) / 1.8
}
Init (fromK, k:, Double) {
Temp = k - 222.1
}
}
let BOL = Cele (fromF:, 100)
let fre = Cele (fromK:, 300)
Print (BOL, FRE)

// destructor 
The //, in contrast to the constructor, automatically calls when the object is freed
class Play {
var coinP: Int
Init (coins:, Int) {
print (, call, )
CoinP = coins
}
Func win (coins:, Int) {
CoinP = 10
}
Deinit {
CoinP = 0
}
}
var, playOne:, Play, =Play (coins:, 100)
print (playOne,.CoinP)
// is not all types defined as nil and must be an optional type,
PlayOne = nil

Latest