12

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?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277

4 Answers4

19

In swift 3, you can use this

var enumValue = Customer.Physics
var str = String(describing: enumValue)
Danil Shaykhutdinov
  • 2,027
  • 21
  • 26
  • 2
    Doesn't work for live values, apparently. Like `avplayeritem.status`. – Jonny Mar 27 '17 at 06:29
  • 1
    `String(describing:)` should *never* be used to convert anything to String, it's not its purpose and will give unexpected results in many cases. – Eric Aya Jun 20 '21 at 10:14
12

Use the rawValue of the enum:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue
vadian
  • 274,689
  • 30
  • 353
  • 361
7

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!

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

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.

Nike Kov
  • 12,630
  • 8
  • 75
  • 122