Reputation: 5969
I recently came across the following:
enum MyEnum {
static let myVariable = "some value"
}
struct MyStruct {
static let myVariable = "some value"
}
and wonder what the static
implies. To my understanding let
already implies the immutability which is then shared by all instances of the enum
/struct
. It sounds to me that this is micromanaging memory consumption, but I'm not sure that I'm missing the underlying point here.
Upvotes: 2
Views: 639
Reputation: 40963
It means myVariable
is a type property – a single property that all instances of the type can use. Essentially a global variable associated with MyEnum
.
In the case of constants declared with let
, this is a way of declaring constants that are scoped to the type that don’t take up space within each instance of that type, i.e.:
struct MySlimStruct {
static let myVariable = "some value"
}
sizeof(MySlimStruct) // returns 0
struct MyFatStruct {
let myVariable = "some value"
}
sizeof(MyFatStruct) // returns 24
In the case of static variables declared with var
, this is a good way of introducing undiagnosable bugs and crashes into your program.
Upvotes: 3