13

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?

3
  • 3
    You need to access its rawValue. cell.textLabel.text = NewProgramDetails.ToMode.rawValue Commented Jul 27, 2016 at 8:31
  • Btw No need to assign the same String to it if it is identical to its case. Commented Jul 27, 2016 at 8:35
  • See also: stackoverflow.com/questions/24701075/… Commented Jul 27, 2016 at 8:38

4 Answers 4

19

In swift 3, you can use this

var enumValue = Customer.Physics
var str = String(describing: enumValue)
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't work for live values, apparently. Like avplayeritem.status.
String(describing:) should never be used to convert anything to String, it's not its purpose and will give unexpected results in many cases.
13

Use the rawValue of the enum:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

Comments

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!

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.