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?
我不知道我的方法(使用标签属性)是最好的,但是无论如何,我需要在我的应用程序中的不同地方进行这种类型的转换。有人知道如何处理这个错误吗?
Thanks!
谢谢!
2 个解决方案
#1
190
Use the rawValue
initializer: it's an initializer automatically generated for enum
s.
使用rawValue初始化器:它是为枚举自动生成的初始化器。
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.
注意:这个答案已经改变。Swift的早期版本使用class方法fromRaw()将原始值转换为枚举值。
#2
3
Use of Enum for comparison like below :
使用Enum进行比较如下:
enum LoanType: Int {
case FHA , VA, CONS, CASH
}
var loanType = LoanType.FHA
Comparison:
比较:
if loanType == .FHA
{
print("FHA")
}
To change value :
改变值:
loanType = .CASH
#1
190
Use the rawValue
initializer: it's an initializer automatically generated for enum
s.
使用rawValue初始化器:它是为枚举自动生成的初始化器。
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.
注意:这个答案已经改变。Swift的早期版本使用class方法fromRaw()将原始值转换为枚举值。
#2
3
Use of Enum for comparison like below :
使用Enum进行比较如下:
enum LoanType: Int {
case FHA , VA, CONS, CASH
}
var loanType = LoanType.FHA
Comparison:
比较:
if loanType == .FHA
{
print("FHA")
}
To change value :
改变值:
loanType = .CASH