gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:31:09 27 4
gpt4 key购买 nike

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

如何从案例中得到“28”?

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

我需要这样的东西:MoveGenres.("selectedgenre").rawValue

最佳答案

首先,这是您定义枚举

的方式
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
}

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

关于swift - 在 Swift 中获取带有字符串的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44474857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com