将字符串转换为枚举而不使用值swift

时间:2015-03-30 20:21:01

标签: swift enums

我正在建立权限系统,下面的emum显示了预付款的可能权限。我从服务器获取权限字符串:advance.answer.view。有没有办法将该字符串转换为枚举Advance.Answer.View

enum Advance {

        case View, Edit

        enum Answer { case View, Edit }
        enum Ride { case View, Edit }
        enum Contact { case View, Edit }
        enum Document { case View, Edit }
        enum Guest { case View, Edit }
        enum Section { case View, Edit, Create }
        enum Member { case View, Edit }
        enum Flight { case View, Edit }
        enum Location { case View, Edit }
        enum Time { case View, Edit }
        enum Event { case View, Edit }

    }

2 个答案:

答案 0 :(得分:1)

你需要使enum成为像

这样的String rawvalue
enum Answer:String {
  case View = "View"
  case Edit = "Edit"
  init(s:String) {
    if s == "xy" { self = .View}
    else { self = .Edit }
  }
  mutating func fromString(s:String) {
    if s == "xy" { self = .View}
  }
}

var answer1 = Answer(rawValue:"View")!
var answer2 = Answer(s:"x")
answer2.fromString("xy")

答案 1 :(得分:1)

您可以将视觉结构修改为:

enum Advance {
    case Answer(view: Bool, edit: Bool)
}

// usage
Advance.Answer(view: false, edit: true)

UPD。 另一个案例:

enum Advance: String {
    case View = "view", Edit = "edit"

    static func getEnumType(value: String) -> EnumProtocol.Type {
        switch value {
            case "contact":
                return Contact.self

            default:
                return Answer.self
        }
    }

    enum Answer: String, EnumProtocol {
        init(rawValue: String) {
            switch rawValue {
                case "edit":
                    self = .Edit

                default:
                    self = .View
            }
        }

        case View = "view", Edit = "edit"
    }

    enum Contact: String, EnumProtocol {
        init(rawValue: String) {
            switch rawValue {
                case "write":
                    self = .Write

                case "edit":
                    self = .Edit

                default:
                    self = .View
            }
        }

        case View = "view", Edit = "edit", Write = "write"
    }
}

EnumProtocol你可以使用rawValue的get函数进行扩展。

protocol EnumProtocol {
    init(rawValue: String)
}

于(31/01/2016)更新

用法:

Advance.getEnumType("contact").init(rawValue: "write") // Advance.Contact.Write
Advance.getEnumType("unknown").init(rawValue: "abc") // Advance.Answer.View