针对Objective-C枚举的新Swift 5警告:如何消除它们? [英] New Swift 5 warnings for Objective-C enums: how to get rid of them?
问题描述
从Xcode 10.2开始,使用我在Objective-C中定义的枚举时,但是在Swift 5 switch语句中,即使我用尽了所有可能的枚举值,我也会收到以下警告.
As of Xcode 10.2, when using enums I've defined in Objective-C, but in a Swift 5 switch statement, I get the following warning, even if I've exhausted all the possible enum values.
Switch covers known cases, but 'MyObjectiveCEnumName' may have additional
unknown values
Xcode告诉我应该通过以下方式解决此问题
Xcode is telling me I should fix this by
Handle unknown values using "@unknown default"
为什么会这样,我该怎么办?
Why is this happening and what can I do about it?
Objective-C枚举
Objective-C enum
typedef NS_ENUM(NSUInteger, CardColor) {
CardColorBlack,
CardColorRed
};
Swift 5 switch语句
Swift 5 switch statement
var cardColor: CardColor = .black
switch (cardColor) {
case .black:
print("black")
case .red:
print("red")
}
推荐答案
TL; DR
如果要像对待Swift对象一样对待Objective-C枚举,则现在需要使用不同的宏NS_CLOSED_ENUM
而不是旧的NS_ENUM
声明它们.更改此设置将使警告消失.
TL;DR
If you want Objective-C enums to be treated just like Swift ones, you now need to declare them using a different macro, NS_CLOSED_ENUM
, versus the old NS_ENUM
. Changing this will make the warning disappear.
从 Swift 5发行说明:
在Swift 5模式下,需要切换在Objective-C中声明的枚举或来自系统框架的枚举来处理未知情况-将来可能会添加的情况,或者可能在Objective-C中私下定义的情况C实现文件.形式上,Objective-C允许将任何值存储在枚举中,只要它适合基础类型即可.可以使用新的@unknown默认案例来处理这些未知案例,如果从开关中省略了任何已知案例,该默认案例仍会提供警告.也可以使用正常的默认情况来处理它们.
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.
如果您在Objective-C中定义了自己的枚举,并且不需要客户端来处理未知情况,则可以使用NS_CLOSED_ENUM宏而不是NS_ENUM. Swift编译器可以识别出这种情况,不需要使用默认大小写的开关.
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枚举的新Swift 5警告:如何消除它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!