【问题标题】:Export swift enum in constantsToExport在 constantsToExport 中导出快速枚举
【发布时间】:2019-05-02 17:04:24
【问题描述】:

在我用于 react-native 的 Swift 本机模块中,我试图将 Swift 枚举导出到 javascript:

@objc(InterfaceOrientationManager)
class InterfaceOrientationManager: NSObject {

  enum InterfaceOrientation: String {
    case landscapeRight
    case landscapeLeft
    case portrait
    case portraitUpsideDown
  }

  @objc
  static func requiresMainQueueSetup() -> Bool {
    return true
  }

  @objc
  func constantsToExport() -> [String: Any]! {
    return [
      "InterfaceOrientation": InterfaceOrientation
    ]
  }

但是这不起作用,我收到错误“类型名称后的预期成员名称或构造函数调用”。屏幕截图在底部。

有没有办法做到这一点?我希望避免做字典:

 let InterfaceOrientation: [String: String] = [
    "landscapeRight": "landscapeRight",
    "landscapeLeft": "landscapeLeft",
    "portrait": "portrait",
    "portraitUpsideDown": "portraitUpsideDown"
  ]

【问题讨论】:

  • 比较stackoverflow.com/a/30480399/1187415:“@objc 枚举必须声明一个整数原始类型
  • 你可能想要字典中的枚举(例如InterfaceOrientation.landscapeRight),而不是枚举类型。
  • 感谢@MartinR - 所以将枚举值导出为字符串的唯一方法似乎是使其成为字典?

标签: swift react-native


【解决方案1】:

像这样从枚举创建字典:

enum InterfaceOrientation: CaseIterable {
    case landscapeRight, landscapeLeft, portrait, portraitUpsideDown
}

var interfaceDictionary: [InterfaceOrientation: String] = [:]
for orientation in InterfaceOrientation.allCases {
    interfaceDictionary[orientation] = "\(orientation)"
}

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 2020-05-19
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多