Why does an @objc enum have a different description than a pure Swift enum?

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

Consider two Swift enums:

enum Foo: Int {     case bar }  @objc enum Baz: Int {     case qux } 

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" 

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?

回答1:

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

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

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.

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!