Swift - Private access level

Introduction

The following code adds the private keyword to both the declarations of a1 and b1 :


class ClassA {
     private  var a1 = 10
}


class ClassB {
     private  var b1 = 20
}

They will now be inaccessible outside the files.

a1 is not accessible to the code in ClassB, and neither can the code in ClassA access b1.

If in ClassA.swift you now add another subclass that inherits from ClassA , then a1 is still accessible:

//these two classes within the same physical file
class ClassA {
     private var a1 = 10
}


class SubclassA: ClassA {
      func myFunction() {
          self.a1 = 5
      }
}

Here, a1 is still accessible within the same file in which it is declared, even though it is declared as private.

Related Topic