Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum with switch in Swift

I'm trying to loop over all tab items to set some properties through a switch using enum:

enum TabItems {
    case FirstTab
    case SecondTab
    case ThirdTab
}

Here's my loop:

for item in self.tabBar.items {
    switch item.tag {
    case .FirstTab:
        println("first tab")
    default:
        println("tab not exists")
    }
}

There is an error: Enum case 'FirstTab' not found in type 'Int!'. How do I properly use enum in this switch statement?

like image 972
Alex Avatar asked Aug 07 '14 07:08

Alex


People also ask

Can you use switch with enum?

An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default. enum constants are accessed using dot syntax. An enum class can have attributes and methods, in addition to constants.

What is the difference between enum and switch in Swift?

First, the switch case uses the name you declared for your variable. The enum holds the logic, and your variable allows you to access the logic. Using the same name in your switch case allows you to access the variable.

Can an enum have a function Swift?

Finally, let's take a look at how enum cases relate to functions, and how Swift 5.3 brings a new feature that lets us combine protocols with enums in brand new ways. A really interesting aspect of enum cases with associated values is that they can actually be used directly as functions.

Can enum conform to Swift protocol?

Yes, enums can conform protocols. You can use Swift's own protocols or custom protocols. By using protocols with Enums you can add more capabilities.


1 Answers

You're getting the error because item.tag is declared as an Int (NSInteger in the API originally) but you're trying to compare it to your TabItems enumeration. You can either use Int values in your switch statement:

for item in self.tabBar.items {
    switch item.tag {
    case 0:
        println("first tab")
    case 1:
        println("second tab")
    default:
        println("not recognized")
    }
}

Or you can convert the tag to your enum, like the example below. (Note that you'll need to update your enumeration's declaration to support .fromRaw().)

enum TabItems : Int {
    case FirstTab = 0
    case SecondTab
    case ThirdTab
}

for item in self.tabBar.items {
    if let tabItem = TabItems.fromRaw(item.tag) {
        switch tabItem {
        case .FirstTab:
            println("first tab")
        case .SecondTab:
            println("second tab")
        default:
            println("not recognized")
        }
    }
}
like image 125
Nate Cook Avatar answered Sep 30 '22 17:09

Nate Cook