class Serializable : NSObject{overrIDe init() { }}class Device : Serializable{ var uuID:String overrIDe init() { println("init ") self.uuID = "XXX" self.uuID = Device.createUUID() println(self.uuID) } class func createUUID() -> String{ return "XXX2" }}var device = Device()@H_301_3@您可以注意到我将createUUID方法实现为静态. @H_301_3@但是为什么我不能以静态的方式从init调用这个方法呢? :
class Serializable : NSObject{overrIDe init() { }}class Device : Serializable{ var uuID:String overrIDe init() { // trIEd // super.init() println("init ") self.uuID = "XXX" self.uuID = self.createUUID() // ERROR self.uuID = createUUID() // ERROR println(self.uuID) // trIEd // super.init() } func createUUID() -> String{ return "XXX2" }}var device = Device()@H_301_3@没有继承它可以正常工作:
class Device { var uuID:String init() { println("init ") self.uuID = "XXX" self.uuID = self.createUUID() println(self.uuID) } func createUUID() -> String{ return "XXX2" }}var device = Device()有两个竞争 initialization safety checks导致您的问题.
Safety check 1 @H_301_3@A designated initializer must ensure that all of the propertIEs introduced by its class are initialized before it delegates up to a superclass initializer.@H_301_3@和
Safety check 4 @H_301_3@An initializer cannot call any instance methods,read the values of any instance propertIEs,or refer to self as a value until after the first phase of initialization is complete.@H_301_3@下面是它的工作原理.
overrIDe init() { super.init() // Fails safety check 1: uuID is not initialized. uuID = createUUID()}@H_301_3@反过来,
overrIDe init() { uuID = createUUID() // Fails safety check 4: cannot call an instance method before initialization is complete. super.init()}@H_301_3@感谢@Ruben in his answer 总结
以上是内存溢出为你收集整理的Swift:为什么我不能从override init调用方法?全部内容,希望文章能够帮你解决Swift:为什么我不能从override init调用方法?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)