如何在Swift中声明特定类类型的枚举?
我正在尝试创建一个类,并使用该类作为我的新枚举的类型,如下所示.
class Abc{ var age = 25 var name = "Abhi" } enum TestEnum : Abc { case firstCase case secondCase } 我在操场上遇到以下错误. error: raw type 'Abc' is not expressible by any literal 所以我尝试遵循这样的RawRepresentable协议. extension TestEnum : RawRepresentable{ typealias RawValue = Abc init?(rawValue:RawValue ) { switch rawValue { case Abc.age : self = .firstCase case Abc.name : self = .secondCase } } var rawValue : RawValue { switch self{ case .firstCase : return Abc.age case .secondCase : return Abc.name } } } 我在此之后遇到以下错误: error: raw type 'Abc' is not expressible by any literal error: instance member 'age' cannot be used on type 'Abc' error: instance member 'name' cannot be used on type 'Abc' 声明某个类类型的枚举的正确方法是什么,而不是对此有明确的想法.有人帮吗? 解决方法
来自Docs
因此,让您的类Abc符合Equatable和上述协议之一.这是一个例子 public class Abc : Equatable,ExpressibleByStringLiteral{ var age = 25 var name = "Abhi" public static func == (lhs: Abc,rhs: Abc) -> Bool { return (lhs.age == rhs.age && lhs.name == rhs.name) } public required init(stringLiteral value: String) { let components = value.components(separatedBy: ",") if components.count == 2 { self.name = components[0] if let age = Int(components[1]) { self.age = age } } } public required convenience init(unicodeScalarLiteral value: String) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: String) { self.init(stringLiteral: value) } } enum TestEnum : Abc { case firstCase = "Jack,29" case secondCase = "Jill,26" } 现在你可以初始化你的枚举了 let exEnum = TestEnum.firstCase print(exEnum.rawValue.name) // prints Jack 有关详细讨论和示例,您可以参考 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- MT 112 Status of a Request for Stop Payment o
- Thinking In React Way - 有限状态机
- postgresql – Postgres函数将查询结果分配给多个
- django获取ajax的post复杂对象的实现方法
- ruby-on-rails – 查询Rails中列不为零的记录
- [AS3]Flash AS3 Bulk Loader跨域加载(CrossDomai
- ruby-on-rails – 用s3和雾上传Carrierwave
- Oracle达人通过OCM 11g 认证的备考经历
- c# – Sql到Linq难度 – 分组,有
- c – 有没有人正在安装GMP MINGW?