Swift:为什么不能在扩展中添加商店属性?内存中的存储属性和计算属性有什么区别

Swift:为什么不能在扩展中添加商店属性?内存中的存储属性和计算属性有什么区别

问题描述:

在扩展章节中,它说:

Swift 中的扩展可以:

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. 但为什么不存储属性?
  2. 内存存储和分配有什么不同?

假设您有一个具有 Int 存储属性的类.创建实例时,分配的存储空间仅包含一个属性.

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

接下来创建一个扩展并添加一个 String 类型的存储属性.创建实例时,存储空间被分配为包含 2 个属性,一个 Int 和一个 String.

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.

只要扩展在作用域内,类就有 2 个属性.扩展不可用的所有地方(例如,因为它是私有的或内部的),该类具有 1 个属性.

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.

此外,您不能假设扩展程序可以公开为随处可见.想想 UIView 类:您创建一个扩展并添加一个存储属性,该属性在您的项目中可见.但是 UIView 也由 UIKit 实例化,例如在 outlet 中,但它无法访问您的自定义扩展.

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.