gpt4 book ai didi

ios - Objective-C 外部常量属性到 Swift 枚举的转换

转载 作者:行者123 更新时间:2023-12-01 16:20:36 26 4
gpt4 key购买 nike

我想用 Contacts 做一个枚举框架 CNLabeledValueCNPhoneNumber类型定义为:

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

但我认为我仍然需要将枚举映射到正确的运行时字符串,我是否还需要以某种方式覆盖枚举的 init?

我想要实现的结果与可能的结果相同:
enum CNLabeledValueType: String {
case home = CNLabelHome
case work = CNLabelWork
case school = CNLabelSchool
case other = CNLabelOther
}

但这是不可能的,因为 Swift 枚举要求“枚举的原始值必须是字符串文字”,因为编译器会提示。那么有什么方法可以使用计算属性进行类似的操作,以便可以按大小写字符串进行切换,并在运行时为每种情况获取正确的字符串计算值?

最佳答案

你可以实现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:在原始值 switch 语句中:
var rawValue: String {
switch self {
case .home:
return CNLabelHome
case .work:
return CNLabelWork
case .school:
return CNLabelSchool
case .other:
return CNLabelOther
}
}

这样,当你想添加一个新标签时,switch语句会出现错误,所以你不会忘记添加另一个case。

关于ios - Objective-C 外部常量属性到 Swift 枚举的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com