简体   繁体   English

Swift - 将 Int 转换为 enum:Int

[英]Swift - Cast Int into enum:Int

I am very new to Swift (got started this week) and I'm migrating my app from Objective-C.我对 Swift 非常陌生(本周开始使用)并且我正在从 Objective-C 迁移我的应用程序。 I have basically the following code in Objective-C that works fine:我基本上在 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.我不知道我的方法(使用 tag 属性)是否是最好的,但无论如何我需要在我的应用程序的不同位置进行这种类型的转换。 Does anyone have an idea of how to get rid of this error?有没有人知道如何摆脱这个错误?

Thanks!谢谢!

Use the rawValue initializer: it's an initializer automatically generated for enum s.使用rawValue初始值设定项:它是为enum自动生成的初始值设定项。

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()将原始值转换为枚举值。

Swift 5斯威夫特 5

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

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
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM