Swift提取两个枚举公共Case并优化函数参数的技术问询
Swift枚举公共Case复用与函数参数优化
一、抽离公共Case实现复用
Swift枚举不支持继承,但可以通过以下两种方式实现公共Case的复用:
1. 定义公共基础枚举+组合枚举
把公共Case单独封装成一个枚举,让Test1和Test2将其作为关联Case,同时保留各自独有的Case,还能兼容原有rawValue用法:
enum CommonCase: String { case common1 = "common1" case common2 = "common2" } enum Test1: String { case common(CommonCase) case new1 = "new1" case new2 = "new2" // 兼容原有rawValue初始化逻辑 init?(rawValue: String) { if let common = CommonCase(rawValue: rawValue) { self = .common(common) } else { switch rawValue { case "new1": self = .new1 case "new2": self = .new2 default: return nil } } } // 重写rawValue保持原有行为 var rawValue: String { switch self { case .common(let common): return common.rawValue case .new1: return "new1" case .new2: return "new2" } } } enum Test2: String { case common(CommonCase) case new3 = "new3" init?(rawValue: String) { if let common = CommonCase(rawValue: rawValue) { self = .common(common) } else if rawValue == "new3" { self = .new3 } else { return nil } } var rawValue: String { switch self { case .common(let common): return common.rawValue case .new3: return "new3" } } }
这种方式彻底复用了公共Case的定义,避免代码重复,同时兼容原有枚举的使用习惯。
2. 协议约束+默认实现
如果不想改动原有枚举的Case结构,可以通过协议统一公共Case的访问逻辑:
protocol HasCommonCases { var commonCase: CommonCase? { get } } enum CommonCase: String { case common1 = "common1" case common2 = "common2" } enum Test1: String, HasCommonCases { case common1 = "common1" case common2 = "common2" case new1 = "new1" case new2 = "new2" var commonCase: CommonCase? { CommonCase(rawValue: self.rawValue) } } enum Test2: String, HasCommonCases { case common1 = "common1" case common2 = "common2" case new3 = "new3" var commonCase: CommonCase? { CommonCase(rawValue: self.rawValue) } }
这种方式无需修改原有枚举结构,仅通过协议间接实现公共逻辑的复用。
二、优化doSomething函数参数
针对仅处理公共Case的doSomething函数,有两种优化方案:
方案1:直接接收公共枚举参数
用CommonCase作为参数,自动转换为Test1和Test2实例执行逻辑:
func doSomething(commonValue: CommonCase) { guard let test1 = Test1(rawValue: commonValue.rawValue), let test2 = Test2(rawValue: commonValue.rawValue) else { // 理论上不会触发,公共Case的rawValue完全匹配两个枚举 return } // 原有业务逻辑 // code doSomethingA(value: test1) doSomethingB(value: test2) // code } // 调用示例 doSomething(commonValue: .common1)
方案2:泛型函数兼容原有枚举输入
如果希望函数能直接接收Test1或Test2实例,同时自动过滤非公共Case,可以写泛型函数:
func doSomething<T: HasCommonCases>(value: T) where T: RawRepresentable, T.RawValue == String { guard let commonCase = value.commonCase else { // 传入非公共Case时直接返回 return } guard let test1 = Test1(rawValue: commonCase.rawValue), let test2 = Test2(rawValue: commonCase.rawValue) else { return } // 原有业务逻辑 // code doSomethingA(value: test1) doSomethingB(value: test2) // code } // 调用示例 doSomething(value: Test1.common1) doSomething(value: Test2.common2)
这种方式更灵活,既兼容原有枚举的调用方式,又能确保只处理公共Case。
内容的提问来源于stack exchange,提问作者Nnnic
相关产品推荐
相关产品推荐

