[英]Swift Enum with multiple types
I am trying to figure out how to duplicate my Java Enum into Swift and i don't know if this is the right way. 我试图弄清楚如何将Java枚举复制到Swift中,我不知道这是否是正确的方法。
My Enum in Java which i am trying to write in Swift: 我想用Swift编写的Java枚举:
public enum EnumDB {
DATABASE_NAME("DataBase"),
DATABASE_VERSION(1);
private String name;
private int value;
private EnumDB(String name) {
this.name = name;
}
private EnumDB(int value) {
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
My Swift Code: 我的Swift代码:
enum EnumDB {
case Name,Version
func getName() -> String{
switch self{
case .Name: return "DataBase"
}
}
func getNumber() -> Int{
switch self{
case .Version: return 1
default: return 0
}
}
}
My questions are: 我的问题是:
thanks 谢谢
You can definitely have an enum
with associated values of different types, which I think can give you what you're looking for. 绝对可以有一个带有不同类型关联值的enum
,我认为这可以为您提供所需的内容。 This is how I might implement your example: 这就是我可能实现您的示例的方式:
enum EnumDB {
case Name(String)
case Version(Int)
}
let namedDB = EnumDB.Name("databaseName")
switch namedDB {
case .Name(let name):
println("Database name is \(name)")
case .Version(let versionNumber):
println("Database version is \(versionNumber)")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.