NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

Question about Enum Values

Forums > 100 Days of Swift

@Donni  

Day 2, Enum Raw values,

Swift will automatically assign each of those a number starting from 0, and you can use that number to create an instance of the appropriate enum case. For example, earth will be given the number 2, so you can write this:

let earth = Planet(rawValue: 2)

What exactly does it mean that you can use that number to create an Instance? I'm also a bit confused of the purpose of an Enum. Why not assign value normally?

Thank you,

   

What exactly does it mean that you can use that number to create an Instance?

It means exactly what is shown in the example you quoted.

You could create an enum value like this:

let earth = Planet.earth

Or you can use its raw value number, like this:

let earth = Planet(rawValue: 2)

I'm also a bit confused of the purpose of an Enum. Why not assign value normally?

Enums allow you to give things meaning by grouping related items and referring to them in a type-safe manner.

So this:

enum Direction {
    case north, south, east, west
}

let whereIsMyHouse = Direction.north

is more meaningful in your code and less likely to result in mistakes than something like this:

let whereIsMyHouse = "north"

or

let whereIsMyHouse = 0 // here we would need to remember that 0 == north, 1 == south, etc.

Also very useful when specifying data types for parameters of functions. This code:

func travel(towards: Direction) {
  // blah blah blah
}

travel(towards: .north)

reads better and is more type safe (i.e., harder for you to make mistakes when coding) than specifying the parameter as a String or an Int.

They also have a lot more functionality that makes them very powerful in Swift. I suggest reading the language guide chapter on Enums for more details.

2      

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.