Using non NS_ENUM objective-C enum in swift

前端 未结 4 1854
你的背包
你的背包 2020-12-10 03:18

I am using the wahoo fitness API and it defines the following objective-C enum:

typedef enum
{
    /** No active connection. */
    WF_SENSOR_CONNECTION_STAT         


        
4条回答
  •  粉色の甜心
    2020-12-10 03:50

    The workaround to use .value to get the underlying integer doesn't work anymore as of Beta 4, as you said.

    Unfortunately an enum is not transferrable to Swift from Objective-C, it needs to be an NS_ENUM.

    I have the same setup as you in a project where I need the enum from an Objective-C framework and use it in Swift.

    The workaround I did was to create an Objective-C category that contains an NS_ENUM and there I transfer the values from the framework enum to my own NS_ENUM.

    Import the category in your bridging header and you should be able to use the enum as you normally would do.

    Something like this:

    typedef NS_ENUM(NSUInteger, ConnectionStatus) {
        ConnectionStatusIdle
    }
    
    - (ConnectionStatus)connectionStatus {
        if [self getConnectionStatus] == WF_SENSOR_CONNECTION_STATUS_IDLE {
            return ConnectionStatusIdle
        }
    }
    

    Then you should be able to use it like this:

    switch myObject.connectionStatus() {
        case .Idle:
            // do something
            break
    }
    

提交回复
热议问题