Faisal Syed Faisal Syed - 17 days ago 5
iOS Question

How to create an enum for pageControl.currentPage?

I want to keep track of my pages using pageControl.currentPage which returns an integer. My switch statement is set up like so:

let currentPage = pageControl.currentPage
switch currentPage {
case 0:

// execute code for first page

case 1:

// execute code for second page

case 2:

// execute code for third page

default: break
}


instead of case "0", "1", and "2", I'd like to be more semantic such as

case FirstPage:
case SecondPage:
case ThirdPage:


How would I go about doing that?

Answer

Your best option is to back the enum with an Int value.

You can declare your enum like so:

enum PageEnum: Int {
  case firstPage = 0
  case secondPage = 1
  case thirdPage = 2
}

You can then use a switch to determine the page value like so:

switch PageEnum(rawValue: currentPage)! {
  case .firstPage:
    print("You're on the first page")
  case .secondPage:
    print("You're on the second page")
  case .thirdPage:
    print("You're on the third page")
  default:
    assert(false, "You shouldn't ever land here")
}
Comments