简体   繁体   中英

Swift: Unable to switch on enum associated value

I'm converting an old Objective C app into SWIFT for learning purposes, and I've stumbled upon a strange problem when trying to provide a switch statement on an enum.

The code looks like this:

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")
}

Where Mood is:

enum Mood: Int16 {
    case THDiaryMoodGood = 0
    case THDiaryMoodAverage = 1
    case THDiaryMoodBad = 2
}

And the representation in mood is stored in a CoreData entity named mood with the type Integer 16 .

My casts directly matched each-other, however when I try and use the switch statement provided above I get the error: Enum case pattern cannot match values of the non-enum type Int16 .

I'm rather confused as to why I'm receiving this error, from my understanding the process should be evaluated like this:

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...
}

Is my thought process or logic flawed here? I'm very confused...any help would be greatly appreciated, thanks!

The problem is that you're passing an Int16 value to the switch. You're setting entry.mood, an Int16, to the raw value 1, but the switch wants your Mood type. So you have a type mismatch.

You can solve it by turning the value into a Mood:

switch Mood(rawValue: entry.mood)! {

Swift enums are not the same as Objective-C enums. In Objective-c, the enum is the backing value , referred to by a different name. In swift, the enum is it's own type, and the value is an associated value (you don't actually need a backing value if you don't want one, in your case it makes sense though).

Have a read of this, it explains things nicely. https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Enumerations.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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