5
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.

macabeus
  • 4,156
  • 5
  • 37
  • 66
  • 2
    Being a `let` just means that it's a constant – it has nothing to do with whether the property is accessible from instance or static scope. Also see [What is the use of “static” keyword if “let” keyword used to define constants/immutables in swift?](http://stackoverflow.com/q/34574876/2976878) – Hamish Feb 23 '17 at 19:18

2 Answers2

17

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.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Thank you for clarification. But, in my case, `let fooValue = 1` have same behavior that `static let barValue = 1`, because both are constantes values, but, `Bar` spent less memory that `Foo`. In what situation is better use code like `Foo`? – macabeus Feb 24 '17 at 02:23
  • 1
    @Macabeus They're not at all the same behaviour. One allocates a single piece of memory for a single value that's bound to the class, the other says to allocate some memory for a new value for every new instance that's created from the class. Their use cases are completely different, but hard to explain until you learn the basics of Object Oriented Programming – Alexander Feb 24 '17 at 02:29
2

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

Gaston Gonzalez
  • 427
  • 3
  • 6