Convert Objective-C enum to Swift String

大兔子大兔子 提交于 2020-07-23 03:11:11

问题


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.


回答1:


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())


来源:https://stackoverflow.com/questions/35318216/convert-objective-c-enum-to-swift-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!