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 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
}
Use the rawValue
initializer: it's an initializer automatically generated for enum
s.
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.