Swift - Cast Int into enum:Int

后端 未结 3 1898
悲&欢浪女
悲&欢浪女 2020-12-23 15:34

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:



        
相关标签:
3条回答
  • 2020-12-23 16:06

    Swift 5

    @IBAction func selectFilter(sender: AnyObject) {
        timeFilterSelected = MyTimeFilter(rawValue: sender.tag)
     }
    
    0 讨论(0)
  • 2020-12-23 16:06

    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
         }
    
    0 讨论(0)
  • 2020-12-23 16:19

    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.

    0 讨论(0)
提交回复
热议问题