How to get enum from raw value in Swift?
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
How to get the name of an enumeration case by its raw value in Swift 4?
You can't get the case name as as String
as the enum's type isn't String
, so you'll need to add a method to return it yourself…
public enum TestEnum: UInt16, CustomStringConvertible {
case ONE = 0x6E71
case TWO = 0x0002
case THREE = 0x0000
public var description: String {
let value = String(format:"%02X", rawValue)
return "Command Type = 0x" + value + ", \(name)"
}
private var name: String {
switch self {
case .ONE: return "ONE"
case .TWO: return "TWO"
case .THREE: return "THREE"
}
}
}
print(TestEnum.ONE)
// Command Type = 0x6E71, ONE
Swift ENUM how to convert rawValue back to Enum case?
First you need to fix your code so that it compiles:
enum Switch : String {
case on = "powerOn"
case off = "powerOff"
var japanswitch : String {
switch self {
case .on : return "onpu"
case .off : return "offu"
}
}
}
Then you can achieve what you are after using:
let japanese = Switch(rawValue:"powerOn")?.japanswitch
Note that japanese
will be an optional; you need to decide how you will handle an invalid raw value.
Get enum from property's raw value
If you want to be able to create an enum based on an instance property value, you need to create your own initializer. With your current implementation, there is no mutual link between haircolor/style and the Character itself. The instance property (haircolor/style) is dependent on the Character, but the other way around there is no relation.
You have to create an initializer for both style and hairColor, I did it for style, you can do it for hairColor in a similar manner.
See the code below:
enum Characters: String {
case Joe, Frank, Jimmy
var hairColor: String {
switch self {
case .Joe: return "Brown"
case .Frank: return "Black"
case .Jimmy: return "Blond"
}
}
var style: String {
switch self {
case .Joe: return "Cool"
case .Frank: return "Bad"
case .Jimmy: return "Silent"
}
}
init(style: String){
switch style {
case "Cool":
self = Characters.Joe
case "Bad":
self = Characters.Frank
default:
self = Characters.Jimmy
}
}
}
Characters(style: "Bad") //initializes Frank
Characters(rawValue: "Joe") //works just like before
Swift - How to get Raw Value from ENUM
You should not use an enum here. Enum cases cannot be referred to dynamically.
While you could do something like this:
enum MembershipLevel: Int, CaseIterable {
case basic = 25
case bronze = 50
case silver = 100
case gold = 500
case platinum = 1000
init?(string: String) {
if let value = MembershipLevel.allCases.first(where: { "\($0)" == string }) {
self = value
} else {
return nil
}
}
}
// usage:
let userValue = snapValue.value as! Int
let membershipString = snapshot.value as! String
if userValue < MembershipLevel(string: membershipString)!.rawValue {
}
It might break in the future as I don't think "\($0)"
producing the enum case name is guaranteed.
I would use a dictionary:
let membershipLevelNameDict = [
"basic": 25,
"bronze": 50,
"silver": 100,
"gold": 500,
"platinum": 1000
]
Usage:
let userValue = snapValue.value as! Int
let membershipString = snapshot.value as! String
if userValue < membershipLevelNameDict[membershipString] ?? 0 {
}
Using this dictionary, you can also create an instance of your enum:
membershipLevelNameDict[membershipString].flatMap(MembershipLevel.init(rawValue:))
But if you want to compare the raw values, just access the dictionary directly like in the first snippet.
How to get Enum's rawValue based on it's attribute value - Swift
You can create an initialiser for your enum that takes the descriptor and returns the enum value for it, then just call enumValue.rawValue
. See the following:
enum Object: Int{
case House1 = 0
case House2 = 1
var descriptor:String{
switch self{
case .House1: return "Cottage"
case .House2: return "House"
}
}
init(descriptor: String) {
switch descriptor {
case "Cottage": self = .House1
case "House": self = .House2
default: self = .House1 // Default this to whatever you want
}
}
}
Now do something like let rawVal = Object(descriptor: "House").rawValue
Can a Swift enum have a function/closure as a raw value?
It's not as straight forward, but you could use OptionSet
, see this page:
Unlike enumerations, option sets provide a nonfailable init(rawValue:) initializer to convert from a raw value, because option sets don’t have an enumerated list of all possible cases. Option set values have a one-to-one correspondence with their associated raw values.
Could be something like this:
func doSomething() {}
func doSomethingElse() {}
struct MyClosures: OptionSet {
static let closureOne = MyClosures(rawValue: doSomething)
static let closureTwo = MyClosures(rawValue: doSomethingElse)
let rawValue: () -> Void
init(rawValue: @escaping () -> Void) {
self.rawValue = rawValue
}
init() {
rawValue = {}
}
mutating func formUnion(_ other: __owned MyClosures) {
// whatever makes sense for your case
}
mutating func formIntersection(_ other: MyClosures) {
// whatever makes sense for your case
}
mutating func formSymmetricDifference(_ other: __owned MyClosures) {
// whatever makes sense for your case
}
static func == (lhs: MyClosures, rhs: MyClosures) -> Bool {
// whatever makes sense for your case
return false
}
}
And so you can use it as:
let myClosures: MyClosures = [ .closureOne, .closureTwo ]
HOWEVER looking at your explanation in the comment:
So I'm trying to find the most efficient way to run a function given the state of a variable.
I think what you actually want is some sort of state machine. Some examples are available here and here
Related Topics
Cagradientlayer Diagonal Gradient
How to Obtain Country, State, City from Reversegeocodecoordinate
Warp \ Bend Effect on a Uiview
How to Compare Two Strings Ignoring Case in Swift Language
What's Dead & Exploded in Swift's Exception Stack
Facebook Share Content Only Shares Url in iOS 9
iOS Floating Video Window Like Youtube App
How to Update Uibutton Title/Text Programmatically
iOS Tesseract Ocr Image Preperation
Xcode 8, iOS 10 - "Starting Webfilter Logging for Process"
How to Detect If Code Is Running in Main App or App Extension Target
MySQL and Swift - Upload Image and File || Would It Be Better to Use Alamofire
Ios: Change the Height of Uisegmentedcontrol
Draw iOS 7-Style Squircle Programmatically