Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27113

Swift how to use enum to get string value

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?

Upvotes: 12

Views: 20728

Answers (4)

Nike Kov
Nike Kov

Reputation: 13698

I've posted a feedback to feedbackassistant with text:

/>

Code:

let test: AVCaptureDevice.Position = .back
print("This is fail: \(test)")

In debugger:

"This is fail: AVCaptureDevicePosition"

Expected:

"This is fail: back"
"This is fail: AVCaptureDevicePosition.back"
...

So the problem is that enum values with associated values doesn't printed. String(test), Mirror(reflecting: test), String(reflecting: test), String(describing: test) doesn't help too.

</

And here is the answer from apple:

This prints AVCaptureDevicePosition(rawValue: 1), i.e., not just the name of the enum, but the raw value too. Swift can't print the text version of this enum value because it doesn't have it at runtime. This is a C-style enum and so all we have is a number, unless we embedded string equivalent values for C enums into the binary, which we have no plans to do.

Upvotes: 0

Danil Shaykhutdinov
Danil Shaykhutdinov

Reputation: 2277

In swift 3, you can use this

var enumValue = Customer.Physics
var str = String(describing: enumValue)

Upvotes: 19

Sweeper
Sweeper

Reputation: 270770

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!

Upvotes: 7

vadian
vadian

Reputation: 285039

Use the rawValue of the enum:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

Upvotes: 12

Related Questions