Why is there a different description in the @objc enumeration than a pure Swift enumeration?

Consider two Swift lines:

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

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

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

Why @objc printing a case with @objc enum print an enumeration name, and when printing a case pure Swift, enumerate the actual name of the case ? Does @objc debug description?

+7
source share
1 answer

This is because @objc are "C-compatible enums" that intentionally do not emit any information about their cases.

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

This implementation-oriented version of the why. Now let me step back one level and ask: why was it implemented in this way? A comment from the emitCaseNames function for C-compatible enums explains this: C-compatible enumerations do not guarantee the mapping from the enum raw value back to the tag, because, unlike Swift renames, they can have several cases where everyone has the same original value.

Now, if you try to declare an enumeration in Swift that duplicates raw values, you will get your manual slap and compiler error. But you should be able to create such an enumeration by declaring an enum in Obj / C, and then importing it into Swift through the bridge.

+1
source

Source: https://habr.com/ru/post/1015344/


All Articles