How to get the name of enumeration value in Swift?

前端 未结 12 1446
太阳男子
太阳男子 2020-11-29 23:53

If I have an enumeration with raw Integer values:

enum City: Int {
  case Melbourne = 1, Chelyabinsk, Bursa
}

let city = City.Melbourne
         


        
12条回答
  •  离开以前
    2020-11-30 00:37

    The String(describing:) initializer can be used to return the case label name even for enums with non-String rawValues:

    enum Numbers: Int {
        case one = 1
        case two = 2
    }
    
    let one = String(describing: Numbers.one) // "one"
    let two = String(describing: Numbers.two) // "two"
    

    Note that this does not work if the enum uses the @objc modifier:

    https://forums.swift.org/t/why-is-an-enum-returning-enumname-rather-than-caselabel-for-string-describing/27327

    Generated Swift interfaces for Objective-C types sometimes do not include the @objc modifier. Those Enums are nevertheless defined in Objective-C, and thus do not work like above.

提交回复
热议问题