在swift编程中没有理解初始化的过程

我正在学习Swfit,我从下面的链接开始学习
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html

我对swift Initialization有疑问。

我的理解如下

1]它的工作方式类似于swift类的构造函数。
2]我们必须初始化其中的所有属性。
3]我们必须调用超类的init()方法。
4]在调用init()之前,我们必须初始化每个属性。
5]初始化后我们可以使用超类的任何成员或方法。

在以上5点的基础上,我创建了一个类。
但由于第3,4和5点有问题。

 /* AdminManagmentSystem - Some class which will consume lots of memory during init */ class AdminManagmentSystem { var adminKey : String init(key:String) { self.adminKey = key; println("Consume lots of memory"); } } /* Person - A base class which can create key. */ class Person { // Some property which will user to create private key. private var privateKey : String = "private" init() { privateKey = "private"; } // function which will calculate key (Comman for all person type) private func calculatekey() -> NSString { return self.privateKey + " key"; } } /* Admin - A sub class which have object of AdminManagmentSystem */ class Admin : Person { // Constant variable let adminmanagmennt : AdminManagmentSystem override init() { self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory super.init(); // Line2 : its compalsurry to call super.init var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init(). self.adminmanagmennt = AdminManagmentSystem(key: adminKey); // Line4 : Again consume lots of memory } } 

下载项目
https://www.dropbox.com/s/afohuxpxxkl5b3c/understandInheritance.zip?dl=0


问题
Line1Line4我必须创建消耗大量内存的AdminManagmentSystem对象。


1]为什么swift强制要求在调用super.init()之前初始化每个属性?
2]如果我使我的属性保持不变为什么swift允许我在init方法中初始化它一次?
3]为什么我必须在init()之前编写override关键字?

回答1 –

从Swift编程语言 –

“如上所述,只有在知道所有存储属性的初始状态后,才会认为对象的内存已完全初始化。 为了满足这个规则,指定的初始化程序必须确保在它移开链之前初始化它自己的所有属性。“

摘录自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/au/jEUH0.l

因此,在对象完全初始化之前,对象处于未定义状态,这可能是“不安全的”,因此Swift要求所有属性在阶段1中初始化。

回答2

初始化函数是一种特殊情况 – 它的工作是将对象设置为其初始状态,因此您可以修改“常量”属性,因为对象仍处于创建过程中 –

“只要在初始化完成时将其设置为一个确定的值,就可以在初始化期间的任何时刻修改常量属性的值。”

摘录自:Apple Inc.“The Swift Programming Language。”iBooks。 https://itun.es/au/jEUH0.l

回答3,因为你重写了一个与超类相同签名的方法(无参数init函数)。 override关键字向编译器指示您知道自己在做什么。 如果编译器默默地让你重新声明一个超类方法,你可能没有意识到你正在这样做并获得意想不到的结果。

在回答有关内存消耗的问题时,ARC将快速回收为该对象的第一个实例分配的内存。 如果这是性能问题,则重构AdminManagmentSystem类非常简单,以便有一个函数来重置现有实例上的键 –

 class Admin : Person { // Constant variable let adminmanagmennt : AdminManagmentSystem override init() { self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory super.init(); // Line2 : its compalsurry to call super.init var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init(). self.adminmanagmennt.key=adminKey; // You can use a property observer function if a simple assignment isn't enough } }