ios 如何从 Swift 中的原始值获取枚举?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36184795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get enum from raw value in Swift?
提问by Leo
I'm trying to get enum type from raw value:
我正在尝试从原始值中获取枚举类型:
enum TestEnum: String {
case Name
case Gender
case Birth
var rawValue: String {
switch self {
case .Name: return "Name"
case .Gender: return "Gender"
case .Birth: return "Birth Day"
}
}
}
let name = TestEnum(rawValue: "Name") //Name
let gender = TestEnum(rawValue: "Gender") //Gender
But it seems that rawValue
doesn't work for string with spaces:
但似乎rawValue
不适用于带空格的字符串:
let birth = TestEnum(rawValue: "Birth Day") //nil
Any suggestions how to get it?
任何建议如何获得它?
回答by vadian
Too complicated, just assign the raw values directly to the cases
太复杂了,直接给case赋值就行了
enum TestEnum: String {
case Name = "Name"
case Gender = "Gender"
case Birth = "Birth Day"
}
let name = TestEnum(rawValue: "Name")! //Name
let gender = TestEnum(rawValue: "Gender")! //Gender
let birth = TestEnum(rawValue: "Birth Day")! //Birth
If the case name matches the raw value you can even omit it
如果案例名称与原始值匹配,您甚至可以省略它
enum TestEnum: String {
case Name, Gender, Birth = "Birth Day"
}
In Swift 3+ all enum cases are lowercased
在 Swift 3+ 中,所有枚举情况都是 lowercased
回答by NoLongerContributingToSE
Full working example:
完整的工作示例:
enum TestEnum: String {
case name = "A Name"
case otherName
case test = "Test"
}
let first: TestEnum? = TestEnum(rawValue: "A Name")
let second: TestEnum? = TestEnum(rawValue: "OtherName")
let third: TestEnum? = TestEnum(rawValue: "Test")
print("\(first), \(second), \(third)")
All of those will work, but when initializing using a raw value it will be an optional. If this is a problem you could create an initializer or constructor for the enum to try and handle this, adding a none
case and returning it if the enum couldn't be created. Something like this:
所有这些都可以工作,但是当使用原始值初始化时,它将是可选的。如果这是一个问题,您可以为枚举创建一个初始化程序或构造函数来尝试处理这个问题,如果无法创建枚举,则添加一个none
案例并返回它。像这样的东西:
static func create(rawValue:String) -> TestEnum {
if let testVal = TestEnum(rawValue: rawValue) {
return testVal
}
else{
return .none
}
}
回答by keshav vishwkarma
You can define enumlike this -
您可以像这样定义枚举-
enum TestEnum: String {
case Name, Gender, Birth
}
OR
或者
enum TestEnum: String {
case Name
case Gender
case Birth
}
you can provide an initmethod which defaultsto one of the member values.
您可以提供一个默认为成员值之一的init方法。
enum TestEnum: String {
case Name, Gender, Birth
init() {
self = .Gender
}
}
In the example above, TestEnum.Name has an implicit raw value of "Name", and so on.
在上面的示例中,TestEnum.Name 具有隐式原始值“Name”,依此类推。
You access the raw value of an enumeration case with its rawValue property:
您可以使用它的 rawValue 属性访问枚举案例的原始值:
let testEnum = TestEnum.Name.rawValue
// testEnum is "Name"
let testEnum1 = TestEnum()
// testEnum1 is "Gender"
回答by BelfDev
With Swift 4.2and CaseIterableprotocol it is not that hard at all!
使用Swift 4.2和CaseIterable协议,它一点也不难!
Here is an example of how to implement it.
这是一个如何实现它的示例。
import UIKit
private enum DataType: String, CaseIterable {
case someDataOne = "an_awesome_string_one"
case someDataTwo = "an_awesome_string_two"
case someDataThree = "an_awesome_string_three"
case someDataFour = "an_awesome_string_four"
func localizedString() -> String {
// Internal operation
// I have a String extension which returns its localized version
return self.rawValue.localized
}
static func fromLocalizedString(localizedString: String) -> DataType? {
for type in DataType.allCases {
if type.localizedString() == localizedString {
return type
}
}
return nil
}
}
// USAGE EXAMPLE
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let dataType = DataType.fromLocalizedString(localizedString: self.title) {
loadUserData(type: dataType)
}
}
You can easily modify it to return the DataType based on the rawValue. I hope it helps!
您可以轻松修改它以根据 rawValue 返回 DataType。我希望它有帮助!
回答by CSE 1994
Display the rawvalue using Enum
使用枚举显示原始值
import UIKit
enum car: String {
case bmw = "BMW"
case jaquar = "JAQUAR"
case rd = "RD"
case benz = "BENZ"
}
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.text = car.bmw.rawValue
}
}
回答by Zvika Ashkenazi
I think this is a quick and clean solution for swift 4.2 (you can c&p to playground)
我认为这是 swift 4.2 的一个快速而干净的解决方案(你可以 c&p 到操场上)
import UIKit
public enum SomeEnum: String, CaseIterable {
case sun,moon,venus,pluto
}
let str = "venus"
let newEnum = SomeEnum.allCases.filter{import UIKit
enum FormData {
case userName
case password
static let array = [userName, password]
var placeHolder: String {
switch self {
case .userName:
return AppString.name.localized // will return "Name" string
case .password:
return AppString.password.localized // will return "Password" string
}
}
}
enum AppString: String {
case name = "Name"
case password = "Password"
var localized: String {
return NSLocalizedString(self.rawValue, comment: "")
}
}
.rawValue == str}.first
// newEnum is optional
if let result = newEnum {
print(result.rawValue)
}
回答by Gurjinder Singh
Here is example of more useable code in swift 4.1
这是 swift 4.1 中更有用的代码示例
##代码##