class MyVIEw: UIVIEw { var collectionVIEw: UICollectionVIEw convenIEnce init () { self.init(frame:CGRectZero) } overrIDe init (frame : CGRect) { super.init(frame : frame) addSubvIEws() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubvIEws() } func addSubvIEws (){ self.collectionVIEw = UICollectionVIEw() }}
现在的问题是我在初始化类内部属性之前不能调用super init(属性’self.collectionVIEw’在super.init调用时没有被初始化),但是我也无法调用我的自定义方法来初始化那些变量super.init,因为它不能在初始化之前使用self.我意识到我可以使实例变量可选,但它似乎不太优雅,因为我知道它将始终被初始化(还有几个,这只是一个简化版本).有没有办法在不制作所有实例变量选项的情况下完成此 *** 作?
编辑:
我想最终我的问题是为什么swift dis-allow在调用super.init之前调用一个方法?有什么区别:
overrIDe init (frame : CGRect) { addSubvIEws() super.init(frame : frame)}final func addSubvIEws (){ self.collectionVIEw = UICollectionVIEw()}
和
overrIDe init (frame : CGRect) { self.collectionVIEw = UICollectionVIEw() super.init(frame : frame)}表格文件:
Swift’s compiler performs four helpful safety-checks to make sure that
two-phase initialization is completed without error:Safety check 1 A designated initializer must ensure that all of the
propertIEs introduced by its class are initialized before it delegates
up to a superclass initializer.
在调用super.init()之前,需要为实例变量设置值.在此 *** 作之后,您将访问调用实例方法.在你的情况下,你可以这样做:
overrIDe init (frame : CGRect) { self.collectionVIEw = UICollectionVIEw() super.init(frame : frame) // Now you can call method self.someMethod()}
ADD for question’s EDIT:
由于安全原因,您无法在super.init()调用之前调用方法.如果你这样做,那么你的方法可以使用一些尚未在父类中初始化的属性
总结以上是内存溢出为你收集整理的swift – ‘在super.init初始化self之前在方法调用中使用self’,不能通过方法调用初始化属性全部内容,希望文章能够帮你解决swift – ‘在super.init初始化self之前在方法调用中使用self’,不能通过方法调用初始化属性所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)