Reputation: 1978
I'm making a permissions system, and the emum below shows the possible permissions for an advance. I get the permissions from the server as a string: advance.answer.view
. Is there any way to convert that string into the enum 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 }
}
Upvotes: 1
Views: 1706
Reputation: 12677
You can modify your visual structure into:
enum Advance {
case Answer(view: Bool, edit: Bool)
}
// usage
Advance.Answer(view: false, edit: true)
UPD. Another case:
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 you can extend with get function of rawValue.
protocol EnumProtocol {
init(rawValue: String)
}
Update at (31/01/2016)
Usage:
Advance.getEnumType("contact").init(rawValue: "write") // Advance.Contact.Write
Advance.getEnumType("unknown").init(rawValue: "abc") // Advance.Answer.View
Upvotes: 1
Reputation: 36313
You need to make the enum a String rawvalue like
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")
Upvotes: 1