Swift - 将Int转换为枚举:Int

Swift  - 将Int转换为枚举:Int

问题描述:

我是Swift的新手(本周开始),我正在从Objective-C迁移我的应用程序。我在Objective-C中基本上有以下代码可以正常工作:

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];
}

将其翻译成Swift时,我做了以下事情:

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'不能转换为'MyTimeFilter'

'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?

谢谢!

使用 rawValue 初始值设定项:它是为 enum s自动生成的初始值设定项。

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

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

参见: Swift编程语言§枚举

注意:这个答案已经改变了。早期版本的Swift使用类方法 fromRaw()将原始值转换为枚举值。

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