Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an instance property only visible to subclass swift

I'm trying to declare a instance property in swift so that it is only visible to it's class and subclasses. I believe this would be referred to as a protected property in other languages. Is there a way to achieve this in Swift?

like image 939
nwales Avatar asked Jan 14 '15 16:01

nwales


People also ask

What is Subclassing in Swift?

Subclassing is the act of basing a new class on an existing class. The subclass inherits characteristics from the existing class, which you can then refine. You can also add new characteristics to the subclass.

How do you override property in Swift?

In swift to override inherited properties or methods in subclass we use override keyword which will tells the compiler to check the overriding method or property definition matches with the base class or not.

What is override in Swift?

Swift version: 5.6. The override is used when you want to write your own method to replace an existing one in a parent class. It's used commonly when you're working with UIViewControllers , because view controllers already come with lots of methods like viewDidLoad() and viewWillAppear() .

What is inheritance Swift?

Inheritance in Swift. In Swift programming language, a class can inherit properties, methods and other characteristics from another class. Inheriting these properties and attributes from one class to another class is known as inheritance.


1 Answers

Access control along inheritance lines doesn't really fit with the design philosophies behind Swift and Cocoa:

When designing access control levels in Swift, we considered two main use cases:

  • keep private details of a class hidden from the rest of the app
  • keep internal details of a framework hidden from the client app

These correspond to private and internal levels of access, respectively.

In contrast, protected conflates access with inheritance, adding an entirely new control axis to reason about. It doesn’t actually offer any real protection, since a subclass can always expose “protected” API through a new public method or property. It doesn’t offer additional optimization opportunities either, since new overrides can come from anywhere. And it’s unnecessarily restrictive — it allows subclasses, but not any of the subclass’s helpers, to access something.

There's further explanation on Apple's Swift blog.

like image 79
rickster Avatar answered Sep 25 '22 01:09

rickster