Switching to Swift - the case label on the switch must have at least one executable expression

I have an enum type that extends String in Swift.

When I try to use switch , I got an error:

The application label on the switch must have at least one executable statement

Here is my code:

 enum UserInfosKey:String { case CameraMyPhotoStream = "CMPS" case CameraICloudActivated = "CICA" case CameraICloudShare = "CICS" case ProjectTodayExtension = "PTE" case ProjectShareExtension = "PSE" case NetworkConnection = "NC" case PhoneLanguage = "PL" case CameraPhotosCount = "CPC" case UserIdentifier = "UI" case VersionHistory = "VH" case Path = "Path" } class UserInfosController: NSObject { func update(key:UserInfosKey, value:String, context:UserDefaultsMainKeys) -> String { switch key { case .CameraICloudActivated: case .CameraICloudShare: case .CameraMyPhotoStream: case .CameraPhotosCount: case .NetworkConnection: case .PhoneLanguage: case .UserIdentifier: return value default: return "" } } } 

enter image description here

I'm sure this is a simple mistake, does anyone see this?

+7
enums ios iphone switch-statement swift
source share
2 answers

There is no implicit failure in the swift switch , so you must explicitly set this:

  case .CameraICloudActivated: fallthrough case .CameraICloudShare: fallthrough case .CameraMyPhotoStream: fallthrough case .CameraPhotosCount: fallthrough case .NetworkConnection: fallthrough case .PhoneLanguage: fallthrough case .UserIdentifier: return value 

Without this, each case has an implicit gap.

Note that swift requires that each key case contain at least one statement - in the absence of an statement, an explicit break must be used (which in this case means "do nothing")

+13
source share

You can have many values ​​for the case, all you have to do is separate them with a comma.

I would also recommend returning nil than an empty string, and making the return function String ?, but that depends on how the function is used.

 func update(key:UserInfosKey, value:String, context:UserDefaultsMainKeys) -> String? { switch key { case .CameraICloudActivated, .CameraICloudShare, .CameraMyPhotoStream, .CameraPhotosCount, .NetworkConnection, .PhoneLanguage, .UserIdentifier: return value default: return nil } } 
+5
source share

All Articles