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:
let birth = TestEnum(rawValue: "Birth Day") //nil
Any suggestions how to get it?
Each raw value for our enum case must be a unique string, character, or value of any integer or floating-point type. This means the value for the two case statements cannot be the same.
We had to do this because Swift doesn't allow us to have both: raw values and associated values within the same enum. A Swift enum can either have raw values or associated values. Why is that? It's because of the definition of a raw value: A raw value is something that uniquely identifies a value of a particular type.
In Swift, an enum (short for enumeration) is a user-defined data type that has a fixed set of related values. We use the enum keyword to create an enum. For example, enum Season { case spring, summer, autumn, winter } Here, Season - name of the enum.
A "raw value" is an unique identifier of a type. It means that you are able to construct your type by ID. For example: XCTAssertEqual(Color.white, Color(rawValue: "#ffffff")) To get raw value use Color.white.rawValue.
Too complicated, just assign the raw values directly to the cases
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
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:
static func create(rawValue:String) -> TestEnum { if let testVal = TestEnum(rawValue: rawValue) { return testVal } else{ return .none } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With