0

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

  • 1
    Does this answer your question? [What makes a property a computed property in Swift](https://stackoverflow.com/questions/39986129/what-makes-a-property-a-computed-property-in-swift). If you have questions like this I would recommend reading [The Swift Programming Language](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html) book, it's a very good resource for both new and experienced swift programmers – Joakim Danielson Jun 23 '20 at 06:23

2 Answers2

2

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)
  1. Creates a variable name with the value name.
  2. Prints the value of variable name [expected output Name]

Whereas

var name = {return "Name"}
print(name)
  1. Creates a variable name with the value of {return "Name"}
  2. Prints that to the console [expected output (Function)]

However

var name = {return "Name"}
print(name())
  1. Creates a variable name with the value of {return "Name"}
  2. Evaluates that function and prints the result [expected output Name]

Therefore

var sum = {return 1+2}
print(sum())
  1. Creates a variable sum with the value of {return 1+2}
  2. Evaluates that function and prints the result [expected output 3]

One last note-- you used single quotes (') but you should declare strings with double quotes (").

Ezra
  • 471
  • 3
  • 14
0

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.
nghiahoang
  • 538
  • 4
  • 10