我有一个enum
类型,在Swift中扩展String
。
当我尝试使用switch
时出现错误:
交换机中的案例标签应至少有一个可执行语句
这是我的代码:
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 ""
}
}
}
我很确定这是一个简单的错误,任何人都能看到它?
答案 0 :(得分:18)
swift switch
语句中没有隐含的落实,因此您必须明确设置:
case .CameraICloudActivated: fallthrough
case .CameraICloudShare: fallthrough
case .CameraMyPhotoStream: fallthrough
case .CameraPhotosCount: fallthrough
case .NetworkConnection: fallthrough
case .PhoneLanguage: fallthrough
case .UserIdentifier:
return value
没有它,每个案例都有隐含的中断。
请注意,swift要求每个switch case包含至少一个语句 - 如果没有语句,则必须使用显式break
(在这种情况下意味着&#34;什么都不做&#34;)< / p>
答案 1 :(得分:6)
您可以为案例设置多个值,您只需要用逗号分隔它们。
我还建议返回一个nil值而不是空字符串,并使函数返回值为String?,但这取决于函数的使用方式。
func update(key:UserInfosKey, value:String, context:UserDefaultsMainKeys) -> String? {
switch key {
case .CameraICloudActivated,
.CameraICloudShare,
.CameraMyPhotoStream,
.CameraPhotosCount,
.NetworkConnection,
.PhoneLanguage,
.UserIdentifier:
return value
default:
return nil
}
}