ios Swift - 将 Int 转换为 enum:Int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25276775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:49:18  来源:igfitidea点击:

Swift - Cast Int into enum:Int

iosxcodeswift

提问by Marcos Duarte

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:

我对 Swift 非常陌生(本周开始使用)并且我正在从 Objective-C 迁移我的应用程序。我基本上在 Objective-C 中有以下代码可以正常工作:

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:

将其翻译为 Swift 时,我执行了以下操作:

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'

“Int”不可转换为“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?

我不知道我的方法(使用 tag 属性)是否是最好的,但无论如何我需要在我的应用程序的不同位置进行这种类型的转换。有没有人知道如何摆脱这个错误?

Thanks!

谢谢!

回答by Jeffery Thomas

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

使用rawValue初始化器:它是为enums自动生成的初始化器。

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

see: The Swift Programming Language § Enumerations

请参阅:Swift 编程语言 § 枚举



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

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

回答by Alok

Swift 5

斯威夫特 5

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

回答by Abraham Gonzalez

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
     }