Swift - Cast Int into enum:Int

IosXcodeSwift

Ios Problem Overview


I am very new to Swift (got started this week) and I'm migrating my app from Objective-C. I have basically the following code in Objective-C that works fine:

typedef enum : int {
    MyTimeFilter1Hour = 1,
    MyTimeFilter1Day = 2,
    MyTimeFilter7Day = 3,
    MyTimeFilter1Month = 4,
} MyTimeFilter;

...

- (void)selectFilter:(id)sender
{
    self.timeFilterSelected = (MyTimeFilter)((UIButton *)sender).tag;
    [self closeAnimated:YES];
}

When translating it to Swift, I did the following:

enum MyTimeFilter : Int {
    case OneHour = 1
    case OneDay = 2
    case SevenDays = 3
    case OneMonth = 4
}

...

@IBAction func selectFilter(sender: AnyObject) {
    self.timeFilterSelected = (sender as UIButton).tag as MyTimeFilter
    self.close(true)
}

By doing that, I get the error :

> 'Int' is not convertible to 'MyTimeFilter'

I don't know if my approach (using the tag property) is the best, but anyway I need to do this kind of casting in different places in my app. Does anyone have an idea of how to get rid of this error?

Thanks!

Ios Solutions


Solution 1 - Ios

Use the rawValue initializer: it's an initializer automatically generated for enums.

self.timeFilterSelected = MyTimeFilter(rawValue: (sender as UIButton).tag)!

see: The Swift Programming Language § Enumerations


NOTE: This answer has changed. Earlier version of Swift use the class method fromRaw() to convert raw values to enumerated values.

Solution 2 - Ios

Swift 5

@IBAction func selectFilter(sender: AnyObject) {
    timeFilterSelected = MyTimeFilter(rawValue: sender.tag)
 }

Solution 3 - Ios

elaborating on Jeffery Thomas's answer. to be safe place a guard statement unwrap the cast before using it, this will avoid crashes

   @IBAction func selectFilter(sender: AnyObject) {
     guard let filter = MyTimeFilter(rawValue: (sender as UIButton).tag) else { 
        return
    }
        timeFilterSelected = filter
     }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcos DuarteView Question on Stackoverflow
Solution 1 - IosJeffery ThomasView Answer on Stackoverflow
Solution 2 - IosAlokView Answer on Stackoverflow
Solution 3 - IosAbraham GonzalezView Answer on Stackoverflow