public vs open? Can a struct be open?
Predict first
Does this compile?
open struct Config {}
- Yes
- No
Mental model. public lets people read your class. open lets them rewrite its methods in their own subclass.
open is for classes and class members that may be subclassed or overridden outside the module. public is visible to importers but closed to inheritance from outside.
Structs, enums, and protocols cannot be open — public is their maximum. There is no inheritance to open.
open means “can be subclassed or overridden outside the module”, which only makes sense for classes and their members.
Common traps
- “A public class can be subclassed by anyone.” Not outside the module, unless it is
open. Inside the module it can. - Marking a class
openby default. It blocks devirtualization and commits you to supporting arbitrary overrides forever.
They might follow up with
- Can a
publicclass haveopenmembers? Syntactically yes, but it is meaningless outside the module: importers cannot subclass apublicclass, so theopenmember is effectivelypublic. - What about protocol requirements? Protocols do not use
open; conformance and requirement visibility are governed bypublic.
Related questions
- 1.7.1 What is the purpose of access control? List the levels.
- 1.1.5 How do you design a public Swift type: struct vs class vs actor vs enum?
← What is the purpose of access control? List the levels. What does package access solve? →