user4357325
user4357325

Reputation:

Swift variable syntax

Sorry for asking a stupid question. But I am confused about this:

var debugMessage: String {
    return "Level 1"
}

Does that code mean the same as:

var debugMessage: String = "Level 1"

Or is it a closure?

Upvotes: 1

Views: 70

Answers (2)

Sweeper
Sweeper

Reputation: 271420

The first:

var debugMessage: String {
    return "Level 1"
}

is a short form of

var debugMessage: String {
    get { return "Level 1" }
}

which is a computed property declaration with only a getter.

And the second is just a simple stored property declaration with an initialisation.

As you can see, one is a computed property and the other is a stored property. So their differences are mostly the same as the differences between computed properties and stored properties.

Here are a few of them.

  • Computed properties with only a getter cannot be set. Stored properties declared with var can be set
  • Computed properties can be placed in extensions. Stored properties cannot.
  • Computed properties doesn't actually occupy memory ("Level 1" isn't stored in memory) until you access it. Stored properties will have their values put into memory when the object is initialised.

Upvotes: 1

glyvox
glyvox

Reputation: 58049

The first example you provided is a computed variable. If it always returns Level 1, then the two examples produce the same result.

However, generally speaking, the second method only provides an initial value to the variable, while a computed variable can change it's return value.

Upvotes: 0

Related Questions