0

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.
8
  • 1
    You can go through this blog post: medium.com/@abhimuralidharan/… or raywenderlich.com/…. A quick Google search should fetch you your answer! Commented Sep 30, 2019 at 19:41
  • 2
    Your question is conceptual and an earlier duplicate can be found here: Difference between struct and enum?. Please read through that! :) Commented Sep 30, 2019 at 19:42
  • 2
    @SamuelSpencer even though that question explains the theoretical difference between structs and enums, Swift enums are much more powerful than the C/C++ ones and hence for this particular question, those differences between Swift enums are the C/C++ ones are quite important Commented Sep 30, 2019 at 19:46
  • 1
    That duplicate doesn't answer OPs question. Commented Sep 30, 2019 at 23:19
  • 1
    @Nitesh Do you have a particular reason why you're worried about the memory layout of these two pieces of code? If there is any difference (which tbh I don't even think is worth bothering to check), it'll be so minuscule, that it'll be completely irrelevant. You should be picking the right tool for the job. If you need an enum, use an enum. If you need a set of static values, use a set of static values. Commented Sep 30, 2019 at 23:25

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.