String to enum mapping in Swift

Viewed 11890

I have an enum defined in Swift as follows:

 public enum Command:String {

   case first = "FirstCommand"
   case second = "SecondCommand"
   ...
   ...
   case last = "lastCommand"
 }

Now I receive a command dictionary from server and I extract the command string from it. The command string would typically be one of the raw values in Command enum or sometimes it could be a command outside the enum(example, new commands are introduced in future versions of client/server but client is still old). In this scenario, what is the way to use switch statement in Swift 3? How do I typecast the command string to enum and handle the unknown commands in default case of switch?

5 Answers

To further expand the different ways you can solve this is by utilizing the CaseIterable protocol.

public enum Command:String, CaseIterable {
    case first = "FirstCommand"
    case second = "SecondCommand"
    case last = "lastCommand"
    case unknown = "UnknownCommand"
    
    static func getCase(string:String) -> Command {
        return self.allCases.first{"\($0.rawValue)" == string} ?? .unknown
    }
}

The usage would be in this manner:

let textCommand = "SecondCommand"
let unknownCommand = "weirdCommand"

// What is the case label of the "textCommand"
print ("\(Command.getCase(string: textCommand))")

// The case label for our "unknownCommand" is
print ("\(Command.getCase(string: unknownCommand))")

You shift the usage of the null coalescing operator to the Command enum instead. It looks a bit overengineered and it probably is. Enjoy!

Related