Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Alexander Certosimo
Alexander Certosimo
1,774 Points

enum variable confusion

hey all

what is the difference between doing both of the following with an enum named Speed that has three members?

var userSpeed = Speed(rawValue: 1)

var userSpeed = Speed.Slow.rawValue

I can not figure out the difference myself so i figured i would ask for help. Thank you

1 Answer

Christopher Augg
Christopher Augg
21,223 Points

Alexander,

       var userSpeed = Speed(rawValue: 1) //UserSpeed is a value of type Speed (Enum Value)
       var userSpeed = Speed.Slow.rawValue //userSpeed is a value of type Int

Hope this helps.

Regards,

Chris

Alexander Certosimo
Alexander Certosimo
1,774 Points

Christopher,

thank you for your reply. that helps a lot. when would it be best to use one or the other? what i struggle most with is understanding situations when i would need to use something specifically

Christopher Augg
Christopher Augg
21,223 Points

Alexander,

Sorry for the late response. You want to use enums for groups of things. For example, if you were writing a program with keyboard commands using the arrow keys, it makes it clearer to use enums instead of numbers for up, down, left, or right.

What does the following mean? Is it error prone?

    var direction = 55

    switch direction {
      case 37 :
          println("Moving \(direction)")
      case 38 :
          println("Moving \(direction)")
      case 39 :
          println("Moving \(direction)")
      case 40 :
          println("Moving \(direction)")
      default:
          println("You can't move in that direction!")
      }

Now lets use enum:

enum Dir : Int {

    case LeftArrow = 37, UpArrow, RightArrow, DownArrow
}


func keyPressed(move : Dir) {

    switch move {
    case .LeftArrow :
        println("Calling function to move left")
    case .UpArrow :
        println("Calling function to move up")
    case .RightArrow :
        println("Calling function to move right")
    case .DownArrow :
        println("Calling function to move down")
    default:
        println("You can't move in that direction!")
    }
}

keyPressed(.DownArrow)

It is much more clear and less prone to errors. Now, you might have to get the rawValue for some reason to pass an actual int to some function, but that is built in and easy to do. Hope this helps.

Regards,

Chris