这是我的代码
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中嵌套枚举的原始值规则是什么?
具有关联值的枚举完全可以符合RawRepresentable
,但您必须手动执行,您已经这样做了,所以这很好。
但是,具有关联值的枚举不能具有原始类型:
enum AccountType : String{
你必须写:
enum AccountType {
相反。请注意,在这种情况下,删除: String
不会损失任何东西,因为: String
所做的只是使AccountType
自动符合RawRepresentable
(出现错误是因为编译器无法自动为具有相关值的枚举执行此操作(。好吧,您已经手动符合RawRepresentable
,所以一开始就不需要: String
!
请注意,这与嵌套枚举无关,而是与具有关联值的枚举有关。