为什么@objc枚举与纯Swift枚举有不同的描述? [英] Why does an @objc enum have a different description than a pure Swift enum?

查看:190
本文介绍了为什么@objc枚举与纯Swift枚举有不同的描述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑两个Swift枚举:

Consider two Swift enums:

enum Foo: Int {
    case bar
}

@objc enum Baz: Int {
    case qux
}

如果我要这些枚举的 print 每个 case ,我会期望相同的结果。相反,我看到一些意想不到的事情:

If I were to print each case of these enums, I would expect the same result. Instead, I see something unexpected:

print(Foo.bar) // "bar\n"
print(Baz.qux) // "Baz\n"

为什么打印一个 @objc 枚举打印枚举名称,同时打印纯粹的Swift枚举的案例打印实际案例名称?添加 @objc 更改枚举的调试描述?

Why does printing a case of an @objc enum print the enum name, while printing the case of a pure Swift enum print the actual case name? Does adding @objc change the debug description of the enum?

推荐答案

那是因为 @objc 枚举是C兼容枚举,它有意地不发布任何关于他们的案例的反射信息。

That is because @objc enums are "C-compatible enums", which intentionally do not emit any reflection information about their cases.

由于Swift是开源的,我们可以自己来看看:

Since Swift is open source, we can nose around to see this for ourselves:

  • @objc enums are treated as C-compatible enums
  • C-compatible enums intentionally don't emit case info for reflection
  • Other enums do emit case info

这是一个版本的为什么,以实现为重点。现在,让我们回过头来一个问题,为什么要这样实现? C-compatible枚举的 emitCaseNames 函数的注释解释了这一点:C兼容的枚举不保证从枚举原始值映射到标签,因为与Swift本机枚举不同,它们可以有多个案例都具有相同的原始值。

That's one version of "why", the implementation-focused. Now, let's step back one level and ask, why was it implemented this way? The comment by the emitCaseNames function for the C-compatible enums explains this: C-compatible enums don't guarantee a mapping from the enum raw value back to the tag, because, unlike the Swift-native enums, they can have multiple cases that all have the same raw value.

现在,如果您尝试在Swift中声明重复原始值的枚举,那么您的手将被打上来,并导致编译错误。但是您应该可以通过在Obj / C中声明枚举来创建这样的枚举,然后将其导入桥梁中的Swift。

Now, if you try to declare an enum in Swift that duplicates raw values, you'll get your hand slapped and a compiler error. But you should be able to create such an enum by declaring the enum in Obj/C and then importing it into Swift over the bridge.

这篇关于为什么@objc枚举与纯Swift枚举有不同的描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆