获取Swift中带有字符串的枚举

获取Swift中带有字符串的枚举,swift,enums,Swift,Enums,我想在用户在选择器视图中选择“操作”后从枚举中获取值。 所以我有一个字符串:selectedGenre=“action” 我怎样才能从这个案子中得到“28” public enum MovieGenres: String { case action = "28" case adventure = "12" case animation = "16" ... } 我需要这样的东西: MoveGenres.(“selectedgenre”).rawValue您可以使用rawValu

我想在用户在选择器视图中选择“操作”后从枚举中获取值。 所以我有一个字符串:
selectedGenre=“action”

我怎样才能从这个案子中得到“28”

public enum MovieGenres: String {
  case action = "28"
  case adventure = "12"
  case animation = "16"
  ...
}
我需要这样的东西:
MoveGenres.(“selectedgenre”).rawValue

您可以使用
rawValue
获取
字符串:

MovieGenres.Action.rawValue // 28
要从字符串中获取它:

let twentyEight = MovieGenres(rawValue: "28")
另一个提示,用小写字母命名您的案例是Swift惯例,如下所示:

 MovieGenres.action.rawValue // 28
更新:

enum MovieGenre: String {
    case action
    case adventure
    case animation

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

let action = MovieGenre(rawValue: "action")?.value // 28
let adventure = MovieGenre(rawValue: "adventure")?.value // 12
let animation = MovieGenre(rawValue: "animation")?.value // 16
let none = MovieGenre(rawValue: "none")?.value // nil

if let value = MovieGenre(rawValue: pickerValue)?.value {
    print(value)
}

首先,这是如何定义
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
        }
    }
}
现在给出一个字符串

 let stringFromPicker = "action"
您可以尝试构建枚举值

if let movieGenre = MovieGenre(rawValue: stringFromPicker) {
    print(movieGenre.code) // 28
}
如您所见,我将
MovieGenres
重命名为
MovieGenres
,事实上,枚举名称应该是单数


也许你想做这样的事。。。在原始价值和你想要得到的案例价值之间存在差异。。。所以,首先你想了解情况:

//Get the value from picker
let selectedValueString = MovieGenres(rawValue: picker.value).myDesiredValue
现在转到枚举:

//The raw Values are the same if you choose String type
public enum MovieGenres: String {
      case action
      case adventure
      case animation

       var myDesiredValue: String{
        switch self{
          case action:
           return "28"
          case adventure:
           return "12"
          case animation:
           return "16"
          }

        }
    }

如何用字符串来选择它?比如:电影类型。rawValue@CoenWalter,
让Twentyweight=MovieGenres(rawValue:“28”)
检查更新的答案,但如果我没有该值该怎么办。用户正在选择:“操作”。我只有那根绳子。从那里我需要28个API函数。所以如果他们选择另一种类型。我需要另一个值。@typeoneerror,不,不是!OP的例子是使用字符串作为原始值,而不是整数。我的答案中的例子工作得非常好。好的,谢谢!但是如果我需要字符串格式的代码呢?
var代码:string{switch self{case.操作:返回“28”case.冒险:返回“12”case.动画:返回“16”//rest}