In Swift, How to Convert a String to an Enum

String to enum mapping in Swift

I'd attempt to create a Command with a raw value of the incoming string, and only use the switch if it succeeds. If it fails, then handle the unknown commands in another routine.

Like:

guard let command = Command(rawValue: incomingString) else {
handleUnknownCommand(incomingString)
return
}

switch command {
case first:
...
}

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
case public
case friends
case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case
is the text of that case’s name.

[...]

enum CompassPoint : String {
case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of
"south", and so on.

You access the raw value of an enumeration case with its rawValue
property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.

Swift ENUM how to convert rawValue back to Enum case?

First you need to fix your code so that it compiles:

enum  Switch : String {
case on = "powerOn"
case off = "powerOff"
var japanswitch : String {
switch self {
case .on : return "onpu"
case .off : return "offu"
}
}
}

Then you can achieve what you are after using:

let japanese = Switch(rawValue:"powerOn")?.japanswitch

Note that japanese will be an optional; you need to decide how you will handle an invalid raw value.

Swift how to use enum to get string value

Use the rawValue of the enum:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

How do I convert an integer to an enum based on its range in Swift?

You already have all you need, you can now define an initializer:

extension Position {
init(_ val: Int64) {
self = Self.convert(val)
}
}

Then you can use your requested:

let readPosition = Position(controller.readVal())

Convert string to enum

Like structs and classes you can add initializers to enums

enum FooEnum: Int {

case fooCase = 1245325
case fooCase2 = 3525325

public init?(_ string: String) {
switch string {
case "fooCase": self = .fooCase
case "fooCase2": self = .fooCase2
default: return nil
}
}
}

let c = FooEnum("fooCase") // `FooEnum c =` is ObjC syntax ;)


Related Topics



Leave a reply



Submit