如何在Swift中从变量中获取枚举

时间:2016-02-09 13:58:48

标签: swift enums

我有一些枚举例如

let variable: String = "SALESMAN"
enum Job
{
   SALESMAN = "Salesman"
   POSTMAN = "Postman"
}

我从数据库获取字符串变量=" SALESMAN",如何使用变量获取枚举Job.SALESMAN?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

let variable: String = "SALESMAN"
// Make your enum back value of String type
enum Job : String
{
    case SALESMAN = "Salesman"
    case POSTMAN = "Postman"
}

let job = Job(rawValue: variable.capitalizedString) //capitalizedString - change your variable to Salesman to match your enum back first case
// Note job is an optional value so you need to unwrap it if needed

print("\(job)")