【问题标题】:How do we return an optional enum value from Swift to Obj-C?我们如何将一个可选的枚举值从 Swift 返回到 Obj-C?
【发布时间】:2017-01-12 17:21:51
【问题描述】:

我们知道如何将 Swift 枚举暴露给 Obj-C:

@objc enum Animal: Int {
    case Cat, Dog
}

但是编译器抱怨以下“不能在 Obj-C 中表示”:

func myAnimal() -> Animal? {
    if hasPet() {
         return .Cat
    } else {
         return nil
    }
}

想法?

【问题讨论】:

  • 在您的枚举中添加case none?
  • 错误信息表达了事实。在 Objective-C 中,不能表示非引用类型的 Optional 值。一种可能的解决方法是将nil-like case 添加到您的枚举中——case none, cat, dog。
  • 我发现一个可选的枚举相当有趣。枚举应该代表几种可能的情况之一。使其成为可选添加了一个母亲,隐藏的状态。正如@CodeDifferent 所建议的那样,我会使用none 案例来代替。你我不确定这是否能解决你的问题。

标签: objective-c swift enums


【解决方案1】:

Swift 中的可选 Int 不会映射到 Objective-C 中的类型。问题是您的 myAnimal() 方法返回的类型无法在 Objective-C 中表示。

在我看来,你有两个选择……

选项1:更改方法的返回类型:

func myAnimal() -> NSNumber? {
  // method body goes here.
}

这看起来不太好,因为在 Objective-C 中你必须这样做:

if (myAnimal().integerValue == AnimalCat) {
  // do stuff here
}

选项 2:在您的枚举中添加一个包罗万象的案例

@objc enum Animal: Int {
  case none = 0
  case cat = 1
  case dog = 2

  init(rawValue: Int) {
    switch rawValue {
    case 1: self = Cat
    case 2: self = Dog
    default: self = None
    }
  }
}

// Updated method signature that makes the compiler happy.
func myAnimal() -> Animal {
  if hasPet() {
     return .Cat
  } else {
    return .None
  }
}

这样,您可以将方法签名更改为不返回可选项,编译器会很高兴。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多