Answers for "swift struct init"

0

swift struct init

//Basically, initialization is giving new values to 
//A new instance of a struct

//Let's take an example of a struct

struct Celsius {
  var temperature: Double
}

//If we try to declare a new instance of this struct

var celsiusInstance = Celsius(//requires temperature parameter)

//There will be an error.
//Swift raises an argument, complaining that there is no variable stored
//For the temperature variable.
  
//You have to do this
 
var celsiusInstance = Celsius(temperature: 10) //required since there is no default value and you have to 
//Declare it yourself

//However, if we add an intializer to the struct

struct Celsius {
  var temperature: Double
  init() {
	temperature = 0
  }
}

//We can simply declare a new instance of this struct without needing to
//Specifically include the temperature parameter
  
var celsiusInstance = Celsius()
  
//Swift will not complain or spit out any errors.
//Since we did not explicitly declare what the temperature parameter would store,
//Swift uses the initializer as the default value, and checks for the temperature variable
//It sees that temperature = 0, and thus declares the new instance with 0 as the temperature variable
  
//That is generally the basics of initializers
//For more info, go here https://docs.swift.org/swift-book/LanguageGuide/Initialization.html
Posted by: Guest on October-28-2021

Code answers related to "Swift"

Browse Popular Code Answers by Language