0

I can't seem to write down the label of a String.

I have an enum with an associated value, as shown here:

public enum HTTPMethod {
    case get
    case post(body: [String: Any])
    case put
    case delete
    case patch
}

I can print the value

let get = HTTPMethod.get
print (get) // get

but what I actually want is the name of the enum, in an uppercase version.

i.e. get would be GET

I'm trying to write an extension for just this:

extension HTTPMethod: CustomStringConvertible {
    public var description: String {
        return String(describing: self)
    }
}

Doesn't work also

extension HTTPMethod: CustomStringConvertible {
    public var description: String {
        return String(describing: self)
    }
}

A version with reflection also doesn't work in my implementation:

extension HTTPMethod: CustomStringConvertible {
    public var description: String {
        let mirror = Mirror(reflecting: self)
        return (mirror.children.first?.label)!
    }
}

So how can I write the uppercase label of the enum?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
WishIHadThreeGuns
  • 1,225
  • 3
  • 17
  • 37

2 Answers2

1

You should add the String representation yourself in your CustomStringConvertible implementation.

public enum HTTPMethod {
    case get
    case post(body: [String: Any])
    case put
    case delete
    case patch
}

extension HTTPMethod: CustomStringConvertible {
    public var description: String {
        switch self {
            case .get: 
                return "GET"
            case .post: 
                return "POST"
            case .put: 
                return "PUT"
            case .delete: 
                return "DELETE"
            case .patch: 
                return "PATCH"
        }
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

I would do this way if it is just an exact upper cased version of the enum cases. If they are different then I would do as David answered.

public enum HTTPMethod {
  case get
  case post(body: [String: Any])
  case put
  case delete
  case patch
  var value: String? {
   return String(describing: self).uppercased()
}
let val = HTTPMethod.get.value
print(val) //prints "GET"