在 swift 中使用非 NS_ENUM 目标 C 枚举 [英] Using non NS_ENUM objective-C enum in swift

查看:30
本文介绍了在 swift 中使用非 NS_ENUM 目标 C 枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 wahoo 健身 API,它定义了以下 Objective-C 枚举:

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

typedef enum
{
    /** No active connection. */
    WF_SENSOR_CONNECTION_STATUS_IDLE,
    /** The connection is in process of being established. */
    WF_SENSOR_CONNECTION_STATUS_CONNECTING,
    /** The sensor connection is established and active. */
    WF_SENSOR_CONNECTION_STATUS_CONNECTED,
    /** The connection was interrupted (usually occurs when fisica is disconnected). */
    WF_SENSOR_CONNECTION_STATUS_INTERRUPTED,
    /** The connection is in process of being disconnected. */
    WF_SENSOR_CONNECTION_STATUS_DISCONNECTING,

} WFSensorConnectionStatus_t;

我找不到快速使用它的方法.我首先尝试对其进行切换/案例但没有成功.我现在只想继续并尝试以下操作:

I can't find a way to use it in swift. I first tried to do a switch/case on it without success. I am at a point I just want to carry on and tried the following:

var connState : WFSensorConnectionStatus_t = WF_SENSOR_CONNECTION_STATUS_IDLE
...
if( connState == WF_SENSOR_CONNECTION_STATUS_IDLE){

但它不编译:

'WFSensorConnectionStatus_t' is not convertible to 'NSObject'

有什么解决方法吗?我读到使用 WFSensorConnectionStatus_t.WF_SENSOR_CONNECTION_STATUS_IDLEWF_SENSOR_CONNECTION_STATUS_IDLE.value 但它在 xcode beta-4 中不起作用.

Any workaround? I read to use WFSensorConnectionStatus_t.WF_SENSOR_CONNECTION_STATUS_IDLE or WF_SENSOR_CONNECTION_STATUS_IDLE.value but it does not work in xcode beta-4.

推荐答案

正如您所说,从 Beta 4 开始,使用 .value 获取底层整数的解决方法不再有效.

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

不幸的是,enum 不能从 Objective-C 转移到 Swift,它需要是一个 NS_ENUM.

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

我在一个项目中与您有相同的设置,我需要来自 Objective-C 框架的 enum 并在 Swift 中使用它.

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.

我所做的解决方法是创建一个包含 NS_ENUM 的 Objective-C 类别,然后我将值从框架 enum 传输到我自己的 NS_ENUM.

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.

在您的桥接头中导入类别,您应该能够像往常一样使用 enum.

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

像这样:

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
}

这篇关于在 swift 中使用非 NS_ENUM 目标 C 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆