How to get enum from raw value in Swift?

Viewed 86921

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?

8 Answers

With Swift 4.2 and CaseIterable protocol it is not that hard at all!

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!

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

    }


}

Here is example of more useable code in swift 4.1

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: "")
  }
}

I think this is a quick and clean solution for swift 4.2 (you can c&p to playground)

import UIKit

public enum SomeEnum: String, CaseIterable {
    case sun,moon,venus,pluto
}

let str = "venus"
let newEnum = SomeEnum.allCases.filter{$0.rawValue == str}.first
// newEnum is optional
if let result = newEnum {
    print(result.rawValue)
}
enum withdrawBalceTimeGenrateError : String ,  Error{
    case insufficientBalance = "Plz Check Balance"
}


withdrawBalceTimeGenrateError.insufficientBalance.rawValue // Plz Check Balance
Related