2

I'm trying to convert iOS error codes to String in Swift 2 (XCode 7.2). But converting to String returns the type name instead of the value name for system enums.

This is what I'm trying:

import CoreLocation
import EventKit

let clError = CLError.LocationUnknown
let clErrorString = "\(clError)"
// EXPECTED: 'LocationUnknown'. OBTAINED: 'CLError'

let ekError = EKErrorCode.CalendarIsImmutable
let ekErrorString = "\(ekError)"
// EXPECTED: 'CalendarIsImmutable'. OBTAINED: 'EKErrorCode'

But with enums declared in Swift, this works as expected:

enum _EKErrorCode : Int {
    case CalendarIsImmutable
}

let _ekError = _EKErrorCode.CalendarIsImmutable
let _ekErrorString = "\(_ekError)"
// EXPECTED: 'CalendarIsImmutable'. OBTAINED: 'CalendarIsImmutable'

I'm trying to avoid a Switch-Case with all posible enum values, or extending system types adding a custom description.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
redent84
  • 18,901
  • 4
  • 62
  • 85
  • Does CLError have any properties that show the error message? – brimstone Feb 10 '16 at 14:46
  • Only visible methods are `rawValue` and `hashValue`. Both return an integer value. – redent84 Feb 10 '16 at 14:49
  • Obviously you'll need to extend the system types or use a switch case, why are you trying to avoid these? – brimstone Feb 10 '16 at 14:53
  • Create a `switch` and assign each enum value a `String`. That's your only option. – Sulthan Feb 10 '16 at 14:59
  • @matt I'm trying to avoid enumerating through all values because it's not future-proof. Any new possible error added to a new iOS version would break the code. – redent84 Feb 10 '16 at 15:02
  • No it wouldn't. That is why you have a default. Or use a dictionary. Just suck it up. – matt Feb 10 '16 at 15:03
  • Possible duplicate of [Getting String name of Objective-C @objc enum value in Swift?](https://stackoverflow.com/questions/40828769/getting-string-name-of-objective-c-objc-enum-value-in-swift) – pkamb Aug 10 '21 at 20:37

1 Answers1

0

This can be achieved in the following way without manually checking the cases by using the ClError.Code extension

extension CLError.Code {
    func getErrorDescription() -> String {
        return String(describing: self)
    }
}

Usage:

let clError = CLError.locationUnknown
print (clError.getErrorDescription())
Md. Ibrahim Hassan
  • 5,359
  • 1
  • 25
  • 45
  • 1
    uhm: tried in these days, on Swift 4.2 and Xcode 10.1, and it seems to me this approach does not work anymore. Had to resort to switch – superjos Jan 22 '19 at 17:10