Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "let" and "static let"? [duplicate]

class Foo {
    let fooValue = 1
}

print(Foo.fooValue) // not work


class Bar {
    static let barValue = 1
}

print(Bar.barValue) // work; print "1"

Why? I expected that Foo example to work, because the value of fooValue is constant, value and memory address known in compilation time. But I need use keyword static to work.

like image 994
macabeus Avatar asked Nov 30 '22 15:11

macabeus


2 Answers

fooValue is an instance property. There's one separate fooValue per every instance (object) of the Foo class.

barValue is a static property. There's one shared barValue that belongs to the class.

Here's a more concrete example. Suppose I had this class:

class Human {
    static let numberOfLimbs = 4
    let name: String
}

What would you expect to happen if I asked you what the name of a Human is? I.e. Human.name. Well, you wouldn't be able to answer me, because there's no one single name of all humans. Each human would have a separate name. You could however, tell me the number of limbs humans have, (Human.numberOfLimbs), which is (almost) always 4.

like image 63
Alexander Avatar answered Dec 03 '22 05:12

Alexander


you don't have to instantiate your class to access static properties

if you wanted to access it in your first class use

Foo().fooValue

generally you want to use static for properties that you want to access without having to instantiate the object every time

like image 38
Gaston Gonzalez Avatar answered Dec 03 '22 05:12

Gaston Gonzalez