Willam Hill
Willam Hill

Reputation: 1602

Swift enums property creation

Are enum properties loaded/computed at creation time? If you have an enum defined as such:

enum Dwarf : Int {
    case Sleepy, Grumpy, Happy, Doc, ..
}

extension Dwarf: Printable {
    var description: String {
        println("description called")
        let names = ["Sleepy", "Grumpy", "Happy", "Doc", ...]
        return names[self.rawValue]
    }
}

Is 'description' created at the same time enum is defined or is it loaded only at run time upon use?

Dwarf.Happy // Enum instantiated - does description exist at this point in time?
println(Dwarf.Happy.description) // property is invoked - is this when description comes into existence?

Upvotes: 3

Views: 1804

Answers (1)

nhgrif
nhgrif

Reputation: 62062

As written, your code wouldn't even compile. I don't know what the playground is showing you--I only know the Playground is far from the best place to test this sort of thing out.

enter image description here

This is what happens when your code is pasted into a non-Playground.

What you actually probably want is something more like this:

enum Dwarf: String {
    case Sleepy = "Sleepy"
    case Grumpy = "Grumpy"
    case Happy = "Happy"
    case Doc = "Doc"
}

extension Dwarf: Printable {
    var description: String {
        return self.rawValue
    }
}

In terms of whether Swift then carries the raw value with each, I don't know, and I'm not sure.

If we use sizeOf on a Swift enum, it tends to give us a value of 1... but there is probably optimization. I imagine if we created an enum with over 256 values, sizeOf may give us 2.

But if we call sizeofValue on the rawValue property of one of the enum values, it gives us different numbers (24 for strings), and this of course makes sense.

sizeOf(Dwarf)                       // gives 1
sizeofValue(Dwarf.Sleepy)           // also gives 1
sizeofValue(Dwarf.Sleepy.rawValue)  // gives 24

I imagine that when your enums are passed around, they've been optimized in terms of size, so an enum with less than 256 values has a size of 1 byte. An enum with less than 65536 values has a size of 2 bytes, and an enum with any more values probably isn't particularly useful.

Meanwhile, calling rawValue probably does some Swift-magic, so the actual backing raw string only exists once you've requested it.

Upvotes: 1

Related Questions