objective-c - Objective-C 枚举 : how to get rid of them? 的新 Swift 5 警告

标签 objective-c swift swift5 xcode10.2

从 Xcode 10.2 开始,当使用我在 Objective-C 中定义的枚举时,但在 Swift 5 switch 语句中,即使我已经用尽了所有可能的枚举值,我也会收到以下警告。

Switch covers known cases, but 'MyObjectiveCEnumName' may have additional 
unknown values

Xcode 告诉我应该通过以下方式解决此问题

Handle unknown values using "@unknown default"

为什么会发生这种情况,我该怎么办?


例子

Objective-C 枚举

typedef NS_ENUM(NSUInteger, CardColor) {
  CardColorBlack,
  CardColorRed
};

Swift 5 switch 语句

var cardColor: CardColor = .black

switch (cardColor) {
case .black:
  print("black")
case .red:
  print("red")
}

最佳答案

长话短说

如果您希望 Objective-C 枚举像 Swift 枚举一样对待,您现在需要使用不同的宏 NS_CLOSED_ENUM 声明它们,而不是旧的 NS_ENUM。更改此项将使警告消失。

上面的例子会变成

typedef NS_CLOSED_ENUM(NSUInteger, CardColor) {
  CardColorBlack,
  CardColorRed
};

迪茨

来自Swift 5 release notes :

In Swift 5 mode, switches over enumerations that are declared in Objective-C or that come from system frameworks are required to handle unknown cases—cases that might be added in the future, or that may be defined privately in an Objective-C implementation file. Formally, Objective-C allows storing any value in an enumeration as long as it fits in the underlying type. These unknown cases can be handled by using the new @unknown default case, which still provides warnings if any known cases are omitted from the switch. They can also be handled using a normal default case.

If you’ve defined your own enumeration in Objective-C and you don’t need clients to handle unknown cases, you can use the NS_CLOSED_ENUM macro instead of NS_ENUM. The Swift compiler recognizes this and doesn’t require switches to have a default case.

关于objective-c - Objective-C 枚举 : how to get rid of them? 的新 Swift 5 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401865/

相关文章:

objective-c - iOS 上的电话号码格式

ios - 禁用 UIControl 一段时间

objective-c - 将 NSData 转换为十六进制 NSString

ios - 如何在 if 语句中使用可选值?

ios - iOS如何实现客户端和服务器端的相互认证?

ios - SwiftUI 登录页面布局

iPhone iOS 使用 UIView animateWithDuration block 执行操作的正确方法是什么?

swift - 如何正确存储时间戳(自 1970 年以来的毫秒数)

ios - "Remind me later"本地通知功能

swift - 如何在 Swift 5.2 函数生成器中使用 buildExpression?