Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift how to use enum to get string value

Tags:

enums

ios

swift

I have enum:

enum NewProgramDetails: String {
    case Description = "Description", ToMode = "To Mode", From = "From", To = "To", Days = "Days"

    static let allValues = [Description, ToMode, From, To, Days]
}

I want to use this enum to display in my cell depend on indexPath:

cell.textLabel.text = NewProgramDetails.ToMode

error: Cannot assign value of type 'ViewController.NewProgramDetails' to type 'String?'

How can I use enum values to assign it to label text as a string?

like image 261
Matrosov Oleksandr Avatar asked Jul 27 '16 08:07

Matrosov Oleksandr


3 Answers

In swift 3, you can use this

var enumValue = Customer.Physics
var str = String(describing: enumValue)
like image 148
Danil Shaykhutdinov Avatar answered Nov 15 '22 06:11

Danil Shaykhutdinov


Use the rawValue of the enum:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue
like image 30
vadian Avatar answered Nov 15 '22 05:11

vadian


Other than using rawValue,

NewProgramDetails.ToMode.rawValue // "To Mode"

you can also call String.init to get the enum value's string representation:

String(NewProgramDetails.ToMode)

This will return "ToMode", which can be a little bit different from the rawValue you assigned. But if you are lazy enough to not assign raw values, this String.init method can be used!

like image 7
Sweeper Avatar answered Nov 15 '22 05:11

Sweeper