Is there a singleline statement that would print String1?
No. Under the covers, C enums are represented by integer values; the C runtime does not have a copy of the string representation. For this to work in Swift, the Swift importer would have to generate these string representation and make them available to the Swift runtime. It does not do that, probably for good reasons [1].
Adding a conformance to
CustomStringConvertable
is one way to address this, but it’s not my preferred way. There’s a general guidance in Swift that you should not conform a type you don’t ‘own’ to a protocol you don’t define. That’s because there’s a potential for confusion if two subsystems within your process add conflicting conformances.
I generally solve this problem by adding a custom property to the enum to return the description I want. For example:
import CoreLocation
extension CLAuthorizationStatus {
var debug: String {
switch self {
case .notDetermined: return "not determined"
case .restricted: return "restricted"
case .denied: return "denied"
case .authorizedAlways: return "authorised always"
@unknown default: return "unknown \(self.rawValue)"
}
}
}
let s = CLAuthorizationStatus.authorizedAlways
print(s.debug)
Note that this use a Swift 5 feature (
@unknown default
) to handle the ‘framework added a new case’ situation. See SE-0192
Handling Future Enum Cases for the details.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] I suspect that the main concerne here is the amount of space used by these strings. Apple’s SDKs contain a lot of enums.