I have doubts about where I should use this declaration:
var name: String = 'Name'
and
var name: String = {return 'Name'}
I saw this in some codes where I work, and I would like to know the difference between these statements
I have doubts about where I should use this declaration:
var name: String = 'Name'
and
var name: String = {return 'Name'}
I saw this in some codes where I work, and I would like to know the difference between these statements
TLDR: One is a function, one is a String
var name: String = "Name" is a "regular" variable assignment. You create a var of type String with the identifier name and assign it the value "Name".
var name: String = {return "Name"} won't compile. You're creating a var of type String but then instead of assigning it a string you're assigning it a function. The curly braces indicate a function.
So...
var name = "Name"
print(name)
name with the value name.Name]Whereas
var name = {return "Name"}
print(name)
name with the value of {return "Name"}(Function)]However
var name = {return "Name"}
print(name())
name with the value of {return "Name"}Name]Therefore
var sum = {return 1+2}
print(sum())
sum with the value of {return 1+2}One last note-- you used single quotes (') but you should declare strings with double quotes (").
The first one is stored property. The second one is computed property.
The difference here is, the code in { } of computed property is execute each time you access it. It has no memory to store the value by itself.
For example, if your viewController has a property:
var label: UILabel { return UILabel() }
// Then you use it as
label.text = "hello" // label 1
label.textColor = .red // another label, label 2
// the label 1 and label 2 are different, it's initialized each time use access it.