In this code I've written a really useless enum that defines a possible Number
with Int or Float.
I can't understand how can I access the value that I set with the association. If I try to print it I get just (Enum Value)
enum Number { case int (Int) case float (Float) } let integer = Number.int(10) let float = Number.float(10.5) println("integer is \(integer)") println("float is \(float)")
In Swift enum, we learned how to define a data type that has a fixed set of related values. However, sometimes we may want to attach additional information to enum values. These additional information attached to enum values are called associated values.
Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Each raw value for our enum case must be a unique string, character, or value of any integer or floating-point type. This means the value for the two case statements cannot be the same.
Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C.
For sake of completeness, enum's association value could be accesed also using if statement with pattern matching. Here is solution for original code:
enum Number { case int (Int) case float (Float) } let integer = Number.int(10) let float = Number.float(10.5) if case let .int(i) = integer { print("integer is \(i)") } if case let .float(f) = float { print("float is \(f)") }
This solution is described in detail in: https://appventure.me/2015/10/17/advanced-practical-enum-examples/
The value is associated to an instance of the enumeration. Therefore, to access it without a switch, you need to make a getter and make it available explicitly. Something like below:
enum Number { case int(Int) case float(Float) func get() -> NSNumber { switch self { case .int(let num): return num case .float(let num): return num } } } var vInteger = Number.int(10) var vFloat = Number.float(10.5) println(vInteger.get()) println(vFloat.get())
Maybe in the future something like that may be automatically created or a shorter convenience could be added to the language.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With