Swift如何使用enum来获取字符串值

时间:2022-05-01 20:54:31

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:

我想使用这个枚举在我的单元格中依赖于indexPath显示:

cell.textLabel.text = NewProgramDetails.ToMode

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

错误:无法指定类型'ViewController.NewProgramDetails'的值来键入'String?'

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

如何使用枚举值将其作为字符串分配给标签文本?

3 个解决方案

#1


9  

Use the rawValue of the enum:

使用枚举的rawValue:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

#2


8  

In swift 3, you can use this

在swift 3中,您可以使用它

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

#3


6  

Other than using rawValue,

除了使用rawValue之外,

NewProgramDetails.ToMode.rawValue // "To Mode"

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

你也可以调用String.init来获取枚举值的字符串表示:

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!

这将返回“ToMode”,它可能与您指定的rawValue略有不同。但是如果你懒得不分配原始值,可以使用这个String.init方法!

#1


9  

Use the rawValue of the enum:

使用枚举的rawValue:

cell.textLabel.text = NewProgramDetails.ToMode.rawValue

#2


8  

In swift 3, you can use this

在swift 3中,您可以使用它

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

#3


6  

Other than using rawValue,

除了使用rawValue之外,

NewProgramDetails.ToMode.rawValue // "To Mode"

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

你也可以调用String.init来获取枚举值的字符串表示:

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!

这将返回“ToMode”,它可能与您指定的rawValue略有不同。但是如果你懒得不分配原始值,可以使用这个String.init方法!