为什么Swift不允许扩展中存储属性? [英] Why does Swift not allow stored properties in extensions?
问题描述
我一直在寻找在扩展中实现存储属性的最佳方法,并遇到了以下问题:
I've been trying to find the best way to implement a stored property in an extension, and came across this question: Swift extension stored properties alternative. However, I have not found a reason why in the discussion or anywhere else. Is there a reason why stored properties are not allowed in Swift? And if so, what is the reason?
推荐答案
扩展用于在不更改内存结构的情况下扩展现有类的功能.它或多或少是语法糖.假设您可以添加存储的属性和方法,那会是什么?除了继承.因此,如果您想添加新的属性和方法,只需从类继承即可.
Extensions are for extending the functionality of an existing class without changing the memory structure. It's more or less syntactic sugar. Imagine you could add stored properties and methods, what would it be? Nothing else but inheritance. So if you like to add new properties and methods just inherit from the class.
这篇关于为什么Swift不允许扩展中存储属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!