Swift enum与嵌套enum,如何实现RawRepresentable协议字符串中的关联值
这是我的密码Swift enum与嵌套enum,如何实现RawRepresentable协议字符串中的关联值,swift,enums,Swift,Enums,这是我的密码 enum AccountType : String{ enum Pattern : String{ case oneTimePassword case password } enum ThirdServicePattern : String{ case facebook case google case line case signInWit
enum AccountType : String{
enum Pattern : String{
case oneTimePassword
case password
}
enum ThirdServicePattern : String{
case facebook
case google
case line
case signInWithApple
}
case phoneNumber(pattern : Pattern)
case email(pattern : Pattern)
case thirdService(pattern : ThirdServicePattern)
}
RawRepresentable
协议的实现如何
当您为AccountType
添加String
时,出现了一个错误“原始类型的枚举不能有带参数的事例”,即使我自己声明rawValue
,它仍然无法编译
enum AccountType : String{
enum BasePattern : String{
case oneTimePassword
case password
}
enum ThirdServicePattern : String{
case facebook
case google
case line
case signInWithApple
}
case phoneNumber(BasePattern) //enum with raw type cannot have cases with arguments
case email(BasePattern) //enum with raw type cannot have cases with arguments
case thirdService(ThirdServicePattern) //enum with raw type cannot have cases with arguments
}
extension AccountType : RawRepresentable {
typealias RawValue = String
/// Backing raw value
var rawValue: RawValue {
return "How?"
}
/// Failable Initalizer
init?(rawValue: String) {
switch rawValue {
case ".PhoneNumber(.oneTimePassword)": self = .phoneNumber(BasePattern.oneTimePassword)
case ".PhoneNumber(.password)": self = .phoneNumber(BasePattern.password)
case ".Email(.oneTimePassword)": self = .email(BasePattern.oneTimePassword)
case ".Email(.password)": self = .email(BasePattern.password)
case ".thirdService(.facebook)": self = .thirdService(ThirdServicePattern.facebook)
case ".thirdService(.google)": self = .thirdService(ThirdServicePattern.google)
case ".thirdService(.line)": self = .thirdService(ThirdServicePattern.line)
default:
return nil
}
}
}
Swift中嵌套枚举的原始值规则是什么?对于关联值tp符合
RawRepresentable
的枚举来说,这是非常好的,但是您必须手动执行,您已经执行了,所以这很好
但是,具有关联值的枚举不能具有原始类型:
你必须写:
enum AccountType {
相反。请注意,在本例中,删除:String
不会丢失任何内容,因为:String
所做的一切都是使AccountType
自动符合RawRepresentable
(发生错误的原因是编译器无法对具有关联值的枚举自动执行此操作)。好吧,您已经手动遵守了RawRepresentable
,因此首先不需要:String
请注意,这与嵌套枚举无关,而与具有关联值的枚举有关
enum AccountType {