Reputation: 13986
According the Apple docs, the new NS_CLOSED_ENUM
macro added for Swift 5 is unchangeable. How is this possible? Can't I just clean the build, add a value, and recompile my app?
Important
Once an enumeration is marked as closed, it's a binary- and source-incompatible change to add a new value. If you have any doubt about an enumeration gaining a private or additional public case in the future, use the NS_ENUM macro instead.
I was able to add a new value to our app and compile just fine (after updating the switch cases).
Upvotes: 3
Views: 1361
Reputation: 7238
Of course it's not uneditable. But what it means is if you do edit it, any code consuming it will require an update before it will compile. In this way, it's just as "editable" as a function signature.
So if you're publishing a library to other developers, you should carefully consider whether you'd want to add new values in a minor update (that wouldn't require any code migration to adopt) or only in a major update (that could require code migration).
But if you're using the enum within one codebase, by all means use NS_CLOSED_ENUM! It makes consumption code cleaner (no "default" cases in your switch that exist only to log "unknown case" and show an error) and the compiler will ensure you update every switch in the codebase when you add the new enum case (instead of, at best, a warning you might miss).
Upvotes: 1
Reputation: 4692
When you use NS_CLOSED_ENUM
, you are making a promise to consumers of your API that the enum will never change, either now in the future.
Of course, there is nothing stopping you from making that change, but if you do, you've now broken that promise. As you said, it compiles fine after updating the switch cases.
If you declare it to be a closed enum you are telling all developers that they never have to worry about it changing. This is useful in Swift 5, which adds an @unknown default
construct in switch
statements to handle unclosed enums.
See this post for more information.
Upvotes: 5