Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Enum with a string in Swift

Tags:

enums

swift

I want to get the value from an enum after the user selected 'action' in a picker view. So I have as string: selectedGenre = "action".

How can I get "28" from the case?

public enum MovieGenres: String {
  case action = "28"
  case adventure = "12"
  case animation = "16"
  ...
}

I need to have something like this: MoveGenres.("selectedgenre").rawValue

like image 573
Coen Walter Avatar asked Nov 30 '22 22:11

Coen Walter


1 Answers

First of all this is how you define your enum

enum MovieGenre: String {
    case action
    case adventure
    case animation

    var code: Int {
        switch self {
        case .action: return 28
        case .adventure: return 12
        case .animation: return 16
        }
    }
}

Now given a string

 let stringFromPicker = "action"

You can try to build your enum value

if let movieGenre = MovieGenre(rawValue: stringFromPicker) {
    print(movieGenre.code) // 28
}

As you can see I renamed MovieGenres as MovieGenre, infact an enum name should be singular.

like image 51
Luca Angeletti Avatar answered Dec 04 '22 16:12

Luca Angeletti