gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:26 26 4
gpt4 key购买 nike

从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com