Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an Enumeration association value in Swift

Tags:

swift

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)") 
like image 592
MatterGoal Avatar asked Jun 17 '14 12:06

MatterGoal


People also ask

What is associated value in enum Swift?

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.

How do you find the value of an enum number?

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.

What is raw value in enum Swift?

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.

What is the default integer value of Swift enumeration cases?

Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C.


2 Answers

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/

like image 133
Marek Gregor Avatar answered Sep 28 '22 19:09

Marek Gregor


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.

like image 26
iQ. Avatar answered Sep 28 '22 18:09

iQ.