Nitesh
Nitesh

Reputation: 2024

Can somebody explain memory allocation for constant defined in struct vs enum?

As we know struct and enum both are value type. We can define constants Like:

struct Foo {
    static let constant = "SomeConstant"
}

print(Foo.constant)

enum Foo: String {
    case constant = "SomeConstant"
}

print(Foo.constant.rawValue)
  1. Which one would make sense based on comparison of memory allocation at runtime ?
  2. Since both seems to be type-properties for me, will they remain forever in stack memory till app is alive.

Upvotes: 0

Views: 479

Answers (1)

Alexander
Alexander

Reputation: 63369

The Swift language doesn't have an official standard to refer to in cases like this. The memory layouts of these two pieces of code are implementation-defined, by the Apple Swift compiler, which is the de-facto standard for the language.

You can look at the emitted SIL or machine code, however, any observations you make are consequences of current implementation details, which are subject to change.

All that is to say: there's no reason why the compiler should handle these differently, but you can't rely on that to not change in the future.

Upvotes: 2

Related Questions