UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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,

3      

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.

5      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.