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

后端 未结 1 1266
孤城傲影
孤城傲影 2021-01-05 04:44

Consider two Swift enums:

enum Foo: Int {
    case bar
}

@objc enum Baz: Int {
    case qux
}

If I were to print each c

相关标签:
1条回答
  • 2021-01-05 05:21

    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:

    • @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

    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.

    0 讨论(0)
提交回复
热议问题