Learn Courses My Dashboard

Structure var declaration

Here is a short snippet of code:

struct MyStructure {
//fancy code here
var temp:MyStructure = MyStructure()
var temp1:MyStructure

Are the two variable declarations the same? To me it looks the code runs the same…
Is one preferred over the other?


Welcome to the community Monty!

They are not the exact same.

var temp:MyStructure = MyStructure()
This creates a variable called temp, and initializes it to a new instance of MyStructure

var temp1:MyStructure
This creates a variable temp1, of type MyStructure but it is not set to a value, so if you print it, it’ll be nil

The first one can be shortened because of type inference, the compiler knows it’s type MyStructure because you’re giving it a value at initialization.
var temp = MyStructure()

Overall I’d say you’ll use the first one more often than the second. (Relatively) Rarely do you declare a variable, but not give it a value

1 Like