Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

properties - 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...