【问题标题】:How to make a Swift enum available in Objective-C?如何使 Swift 枚举在 Objective-C 中可用?
【发布时间】:2019-08-07 07:19:44
【问题描述】:

我有这样的枚举:

public enum TrackingValue {

    case constant(String)
    case customVariable(name: String)
    case defaultVariable(DefaultVariable)

    public enum DefaultVariable {
        case advertisingId
        case advertisingTrackingEnabled
        case appVersion
        case connectionType
        case interfaceOrientation
        case isFirstEventAfterAppUpdate
        case requestQueueSize
        case adClearId
    }
}

是否有人对如何在 Objective-C 中提供类似的东西有任何最佳实践建议?

谢谢

【问题讨论】:

  • 你是否尝试在'public'标签之前添加@objc标签?
  • Objective-C 中的枚举是 Int 在 Swift 中是对象
  • @Azat 是的,当然,但我得到一个错误 '@objc' enum must declare an integer raw type ,我不知道如何将这种情况转换为在 Objective C 中可用。

标签: objective-c swift enums


【解决方案1】:

你只能使用可以在 objc 中表示的枚举:

  1. 没有嵌套枚举的枚举
  2. 不带参数的枚举
  3. 枚举原始类型 应该是整数

因此你只能创建另一个枚举,巫婆可以在 objc 中表示,只需添加方法来转换它:

public enum TrackingValue {
  ...

  func toObjc() -> ObjcEnum {
     ...
  }
}

并在某处创建快速方法到另一边:

func convert(_ type: ObjcEnum) -> TrackingValue {
   ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 2015-08-09
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多