Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Why cannot add store property in extension? What's the different between store property and computed property in memory

In Extensions chapter, it says:

Extensions in Swift can:

Add computed properties and computed static properties Define instance methods and type methods Provide new initializers Define subscripts Define and use new nested types Make an existing type conform to a protocol

  1. But why not stored properties?
  2. What's the different in memory storage and allocation?
like image 862
Scott Lee Avatar asked Dec 05 '22 22:12

Scott Lee


1 Answers

Say you have a class with an Int stored property. When an instance is created, the storage is allocated to contain one property only.

Next you create an extension and add a stored property of type String. When you create an instance, the storage is allocated to contain 2 properties, an Int and a String.

As long as the extension is in the scope, the class has 2 properties. All places where the extension is not available (for instance because it is private or internal), the class has 1 property instead.

It's easy to understand that the same class in two different contexts is not compatible with itself.

Also, You cannot make the assumption that the extension can be made public to be visible everywhere. Think of the UIView class: you create an extension and add a stored property, which is visible in your project. But UIView is also instantiated by UIKit, for instance in outlets, but it has no access to your custom extension.

See the difference? Adding a new stored property actually creates a new class type which is different than the original one - so it is not allowed. There's a specific tool for that: inheritance.

like image 65
Antonio Avatar answered May 17 '23 23:05

Antonio