Object Oriented Programming

Access Modifiers in Swift

Access modifiers restrict or permit direct access to a member (method, class, field, etc.) outside of its scope.

modifier memberDeclaration //memberDeclaration is the method, class, variable, or other member declaration


Members with the 'public' modifier can be accessed directly outside of its entity (file, class, structure).

Members with the 'private' modifier can only be accessed within its own class or structure.

Members with the 'internal' modifier can be accessed from anywhere within the source file. All members without a modifier are implicitly given the 'internal' modifier.

public class Car { 
    private var speed: Double
    public var wheels = 4
    /*these methods can access and modify the private variable
    because they are within its class */
    init(speed: Double) { 
        self.speed = speed
    //this public method is a 'getter', it returns the value contained in a private variable
    func getSpeed() -> Double { 
        return speed
    public void carBrake(slow: Int) { 
        speed -= slow 
var sedan = Car(80);
//wheels is a public variable, so it can be accessed directly outside the class itself
print "Number of wheels: \(sedan.wheels)"
//speed cannot be accessed in this way
//Instead, a public method within the class is used to access the variable's value
print "Speed: \(sedan.getSpeed)"

< Class Declaration   |   Initializer >

© 2019 SyntaxDB. All Rights Reserved.