我想用Contacts
框架CNLabeledValue
的CNPhoneNumber
类型定义一个枚举:
// Generic labels
CONTACTS_EXTERN NSString * const CNLabelHome NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelWork NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNLabelSchool NS_AVAILABLE(10_15, 13_0);
CONTACTS_EXTERN NSString * const CNLabelOther NS_AVAILABLE(10_11, 9_0);
我做了这样的事情:
enum CNLabeledValueType: String {
case home
case work
case school
case other
var rawValue: String {
switch self {
case .home:
return CNLabelHome
case .work:
return CNLabelHome
case .school:
return CNLabelSchool
default:
return CNLabelOther
}
}
}
但是我想我仍然需要将枚举映射到正确的运行时字符串,是否还需要以某种方式覆盖枚举的初始化?
我想达到的结果将与可能的结果相同:
enum CNLabeledValueType: String {
case home = CNLabelHome
case work = CNLabelWork
case school = CNLabelSchool
case other = CNLabelOther
}
但是这是不可能的,因为Swift枚举要求编译器抱怨“枚举的原始值必须是String文字”。那么,是否有任何方法可以使用计算属性来进行相似的转换,从而可以按大小写字符串进行切换,并在每种情况下在运行时获取正确的字符串计算值?
您可以像这样实现init(rawValue:)
:
init?(rawValue: String) {
switch rawValue {
case CNLabelHome:
self = .home
case CNLabelWork:
self = .work
case CNLabelSchool:
self = .school
case CNLabelOther:
self = .other
default:
return nil
}
}
还请注意,您在rawValue
实现中有错字。第二种情况应返回CNLabelWork
。我还建议不要在原始值切换语句中使用default:
:
var rawValue: String {
switch self {
case .home:
return CNLabelHome
case .work:
return CNLabelWork
case .school:
return CNLabelSchool
case .other:
return CNLabelOther
}
}
这样,当您要添加新标签时,switch语句将出现错误,因此您不会忘记添加其他情况。