Search code examples
swiftnslog

How can I get similar print result of NSLog for int enum in swift?


enum ImportType: Int {
    case First = 1
    case None
    case Original
}

var type: ImportType = .First

print(type)                     --------------------> This will output "First"

NSLog("%@", String(type)        --------------------> I can't do this.

NSLog("%d", type.rawValue)      --------------------> This will output "1"

Hi All,

I want to get similar result of NSLog as the print function, it more readable for people, but I can't found a way to do this, I got some result that need to do additional handling inside the enum, but I am using other body's source code and just want to collect some information directly.

Are there easy transform way to do what I want?

Thanks~~

Eric


Solution

  • print uses String.init(describing:) under the hood to convert whatever you give it to a String, so you can do that too:

    NSLog("%@", String(describing: type))
    

    But really though, the enum should conform to CustomStringConvertible:

    enum ImportType: Int, CustomStringConvertible {
        
        case First = 1
        case None
        case Original
        
        var description: String {
            switch self {
            case .First:
                return "First"
            case .None:
                return "None"
            case .Original:
                return "Original"
            }
        }
    }
    

    and you should not rely on this default behaviour of String(describing:), because its behaviour is not specified unless the type conforms to TextOutputStreamable, CustomStringConvertible or CustomDebugStringConvertible. See here for more info.