swift - 编写一个泛型函数以从 Swift 中的多个枚举中获取公共变量
问题描述
我想编写一个可以访问多个枚举案例及其公共变量的通用方法。
enum MyEnum:String,CaseIterable {
case a = "a"
var ourVar:MyAnotherEnum {
switch self {
case .a:
return MyAnotherEnum.a1
}
}
}
enum MyAnotherEnum:String,CaseIterable {
case a1 = "a1"
}
enum YourEnum:String,CaseIterable {
case b = "b"
var ourVar:YourAnotherEnum {
switch self {
case .b:
return YourAnotherEnum.b1
}
}
}
enum YourAnotherEnum:String,CaseIterable {
case b1 = "b1"
}
我和你的枚举都具有“ourVar”作为常见。现在,我想编写一个方法,如果我传递一个枚举,它可以打印所有值。像这样的东西:
printAll(MyEnum.self) //Should print "a" and "a1"
我试着像迭代一个枚举一样:
func printAll<T>(_ id:T.Type) where T:RawRepresentable, T:CaseIterable {
for c in T.allCases {
print(c.rawValue) //Prints the value correctly
print(c.ourVar) //Throws error "Value of type 'T' has no member 'ourVar'"
}
}
我的确切期望是,printAll(myEnum)
应该打印“a”和“a1”。
我的代码流解释起来很复杂,但我绝对需要这种方法来节省数千行代码。任何人都可以帮助我吗?
解决方案
首先,您需要创建一个CommonEnum
protocol
withourVar
作为这样的要求之一,
protocol CommonEnum {
associatedtype T
var ourVar: T { get }
}
protocol
现在符合上述MyEnum
和YourEnum
,
enum MyEnum: String, CaseIterable, CommonEnum {
//....
}
enum YourEnum: String,CaseIterable, CommonEnum {
//....
}
接下来,printAll(_:)
方法将是
func printAll<T>(_ id: T.Type) where T: CommonEnum & RawRepresentable & CaseIterable {
for c in T.allCases {
print(c.rawValue)
print(c.ourVar)
}
}
例子:
printAll(MyEnum.self) //prints a and a1
推荐阅读
- c# - 在转换 C# 之前检查 DbNull
- python - Python如何在不取消缩进的情况下注释掉for语句
- android - 无法使用媒体控制器将媒体项目添加到队列
- oauth-2.0 - 在 Authlib 的示例 oauth2 服务器中,为什么 user_id 绑定到客户端元数据?
- mongodb - MongoDB + Postgres(或者我需要一个图形数据库吗?)
- java - org.sf.beans.factory.NoSuchBeanDefinitionException:没有可用的 X 类型的合格 bean
- c++ - c++ print Hexadecimal with int word, ostream &os
- php - 给定一个字符串,它是一系列 excel 单元格“A1:F1”,如何在 PHP 中插入这个范围?
- bash - 编辑 uniq -c (Bash) 的输出
- java - 从 Android 中的 Intent 选择时,文件返回空 ("")