How to get the name of enumeration value in Swift?

前端 未结 12 1449
太阳男子
太阳男子 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:43

    Introspection in Swift Enums seems to work partially.

    I saw @drewag's response, and found that an Enum with no rawValues can indeed have introspection in Swift 5.X with Xcode 11.5. This code works.

    public enum Domain: String {
        case network
        case data
        case service
        case sync
        var description: String {
            return "\(self)"     // THIS INTROSPECTION WORKS
        }
    }
    enum ErrorCode: Int, CustomStringConvertible {
        case success = 200
        case created = 201
        case accepted = 202
        case badRequest = 400
        case unauthorized = 401
        case forbidden = 403
        case notFound = 404
        var code: Int {
            return self.rawValue
        }
        var description: String {
            return "\(self)"      //THIS DOES NOT WORK - EXEC_BAD_ACCESS
        }
    }
    let errorCode = ErrorCode.notFound
    let domain = Domain.network
    print(domain.description, errorCode.code, errorCode.description)
    

    Replace the "\(self)" for "string" in the second Enum and you will get this printout: network 404 string

    NOTE: Using String(self) instead of "\(self)" in the first Enumwill require the Enum to conform to theLosslessStringConvertible` protocol, and also add other initializers, so a string interpolation seems to be a good workaround.

    To Add a var description: String to the enum, you will have to use a Switch statement will all the enum cases as pointed before

    var description: String {
        switch self {
        case .success: return "Success"
        case .created: return "Created"
        case .accepted: return "Accepted"
        }
    }
    

提交回复
热议问题