Getting an enum to print in different case

If I have an enum and print it:

enum Method:UInt8 {
	case get = 1
	case put = 2
	case post = 3
	case delete = 4
	case copy = 5
}
let method:Method = .post
print("method is \(method)")

Swift somehow knows how to print the method as "post" rather than "3". But I'd like to make it print in all caps. But I don't want to change the definition of the cases. Is this possible? Can I progrommatically invoke the same thing that the \() seems to do so that I can then caps it? E.g.

print("METHOD is \(method.description.uppercased())")

But enum's don't seem to respond to description? Missing some of the glue magic understanding that allows Swift to print enums with their source keys I guess.

Conform to CustomStringConvertible

1 Like

Simplest way is to use string interpolation:

let name = "\(method)".uppercased()
print(name) // POST
2 Likes

Do you have to use UInt8 as your raw value? If you use a string, you get this for free:

enum Method: String {
    case get = "GET"
    case put = "PUT"
    case post = "POST"
    …
}

print(Method.post)                  // POST
print(MemoryLayout<Method>.size)    // 1

Note that using a string doesn’t make the enum bigger in memory.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

2 Likes
Terms of Service

Privacy Policy

Cookie Policy