To initialize instance attributes of struct, class, and other types.
Default constructor
[HTML]View plaincopy
- Struct Fahrenheit {
- VaR temperature: doubleinit (){
- Temperature = 32.0
- }
- }
VaR F = Fahrenheit () // call the default constructor Init (). No parameter is returned.
[HTML]View plaincopy
- Println ("the default temperature is \ (F. Temperature) deg F ahrenheit ")
- // Prints "the default temperature is 32.0 ° Fahrenheit"
Custom Constructor
The definition class has two constructors: Init (fromfahrenheit :) and 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)
The Destructor is opposite to the constructor and called when the object is released. Use the keyword deinit. The syntax is as follows:
[HTML]View plaincopy
- Deinit {
- // Perform thedeinitialization
- }
Instance:
[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 discussion forum: http://www.cocoagame.net
Welcome to the swift technology exchange group: 362298485