Real estate creation Swift enums
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 the "description" created at the same time as the enum or is it only loaded at runtime when used?
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?
source to share
As written, your code doesn't even compile. I don't know what the playground is showing - all I know is that the Playground is far from the best place to check out this thing.
This is what happens when your code is inserted into a non-playing field.
What you really want is something more:
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 Swift then passing the original value with each one, I don't know, and I'm not sure.
If we use sizeOf
on Swift enum
, it tends to give us a value of 1 ... but there is probably an optimization. I guess if we created an enum with more than 256 values, it sizeOf
might give us 2
.
But if we call a sizeofValue
property of rawValue
one of the values enum
, it gives us different numbers (24 for strings), and that certainly makes sense.
sizeOf(Dwarf) // gives 1
sizeofValue(Dwarf.Sleepy) // also gives 1
sizeofValue(Dwarf.Sleepy.rawValue) // gives 24
I assume that when yours is enums
passed they are optimized in terms of size, so an enum with less than 256 values is 1 byte in size. enum
with size less than 65536 is 2 bytes in size, and enum
with any values probably not particularly useful.
Meanwhile, the call rawValue
is probably doing some Swift-magic, so the actual support baseline only exists after it's been requested.
source to share