[Swift] Access Level

You wouldn't like to open your whole project to the public or you'd like to share the data only into your module. How could we handle this issue?

Swift has five levels of accessing data. on the levels, you can give different authorities.

 

1. Private

private is the most encapsulated level. If you set the private variable, you can access the data only in the bracket, class.

e.g private var numberOfPizza: Int = 4

 

2. fileprivate

Fileprivate guarantees a variable declared as filepriavte can share in the file such as ~~.swfit

e.g fileprivate var shareInFileOnly: bool = true

 

3. Internal -> default level

Internal level means "in the module" you can use the data only in the module. you can share it to other files, if they are in the same module

e.g. var inTheModule: bool = true

 

From 1-3 level, it isn't expose to the public users. However, below this sentence, you supposed to be careful that other developer can access the data

 

4. Public

if you want to access your data out of module, what should you do? For instance, when you use a cocopod module, the cocopod data is declared  by public

e.g. public var shareWithinModules: bool = true

5. Open

Open level provides additional freedom into the classes and methods. You can open a subclasses, overrides the class.

e.g. open class openClass { }

 

Access levels regard almost everything in Swift: Classes, structures, enumerations, properties, methods, protocols. Applying different access levels is not difficult; it’s just a matter of writing a special keyword, a specifier, right before the entity you need it. In a more general context, it’s mostly a matter of decision making than a matter of doing something programmatically heavy or intensive.

Leave a Comment

ko_KRKorean