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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With