Search code examples
swiftobjective-cenumsenumeration

How to call a Swift enum function to get string in objc?


I have this enum in Swift SDK, and need to print the description as a debug message.

@objc public enum ResultCode : UInt16 {
    case noError = 0x0000

    @objc public func description() -> String {
        switch self {
        case .noError:
            return "No Error"
        }
    }
}

The description can not be called in Objc like this:

[taskManager.sendRequest requestWithCompletion:^(ResultCode resultCode) {
    NSString *resultCodeDescription = [resultCode description];//Bad receiver type 'ResultCode' (aka 'enum ResultCode')
    NSLog(@"Result code description: %@", resultCodeDescription);
}];

I know that adding a ResultCode extension in Swift file and a @objc function is a solution, but I prefer to solve this in objc file, how can I approach this?


Solution

  • @objc for bridging Swift enum to Objective-c enum only supports integer types as the raw value.

    @objc public func description() -> String { ... }
    

    The above code will throw an error at compile time:

    @objc can only be used with members of classes, @objc protocols, and concrete extensions of classes

    You can try this approach, define a class in Swift to add objc annotation:

    @objc class ResultCodeReader: NSObject {
        @objc static func getDescription(from resultCode: ResultCode) -> String {
            resultCode.description()
        }
    }
    

    Then you're able to get the ResultCode description from Objective-c:

    NSString *desc = [ResultCodeReader getDescriptionFrom:ResultCodeNoError];