我出于学习目的将旧的Objective C应用程序转换为SWIFT,并且在尝试在枚举上提供switch语句时偶然发现了一个奇怪的问题。
代码如下:
switch entry.mood {
case let Mood.THDiaryMoodGood:
self.moodImageView.image = UIImage(named: "icn_happy")
case let Mood.THDiaryMoodAverage:
self.moodImageView.image = UIImage(named: "icn_average")
case let Mood.THDiaryMoodBad:
self.moodImageView.image = UIImage(named: "icn_bad")
default:
self.moodImageView.image = UIImage(named: "icn_happy")
}
心情在哪里:
enum Mood: Int16 {
case THDiaryMoodGood = 0
case THDiaryMoodAverage = 1
case THDiaryMoodBad = 2
}
情绪表示形式存储在名为
mood
的CoreData实体中,类型为Integer 16
。我的演员阵容彼此直接匹配,但是当我尝试使用上面提供的switch语句时,出现错误:
Enum case pattern cannot match values of the non-enum type Int16
。对于我为什么会收到此错误,我感到很困惑,据我的理解,应该这样评估流程:
entry.mood = 1
switch(1) {
// Int16: 0 returned from enum - would evaluate false and fall through to case B
case Mood.THDiaryMoodGood:
self.mood.image = ...
// Int16: 1 returned from enum - would evaluate true and set the icon
case Mood.THDiaryMoodAverage:
self.mood.image = ...
// Other cases not evaluated as we returned true...
}
我的思考过程或逻辑是否存在缺陷?我很困惑...任何帮助将不胜感激,谢谢!
最佳答案
问题在于您要将Int16值传递给交换机。您将Int16的entry.mood设置为原始值1,但是交换机需要您的Mood类型。所以你有一个类型不匹配。
您可以通过将值转换为心情来解决它:
switch Mood(rawValue: entry.mood)! {