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?
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.
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.
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.
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.
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")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With