简体   繁体   中英

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?

In swift 3, you can use this

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

使用枚举的rawValue

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

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!

I've posted a feedback to feedbackassistant with text:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM