在Swift的财产申报中引用自我
我试图用下面的代码声明和初始化一个属性。
class ClassName: UIViewController { private let doneButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButtonDidTapped") func doneButtonDidTapped() { println("Ulala!") } }
但是,我得到以下错误。
Cannot find an initializer for type 'UIBarButtonItem' that accepts an argument list of type '(title: String, style: UIBarButtonItemStyle, target: ClassName -> () -> ClassName, action: String)'
有人知道这是怎么回事? 我应该放弃尝试与声明内联初始化属性,并在init()方法上进行初始化?
正如@giorashc所说,由于swift的2阶段初始化,自我还没有初始化,所以你不能这样做。
但我认为你可以创build一个懒惰的初始化:
lazy private var doneButtonItem : UIBarButtonItem = { [unowned self] in return UIBarButtonItem(title: "Done", style:UIBarButtonItemStyle.Plain, target: self, action: "doneButtonDidTapped") }()
由于swift的两阶段初始化,您需要初始化父类,然后才能在inheritance类中使用self
。
在你的实现中, self
还没有被父类初始化,所以你说你应该把它移动到你的视图控制器的init
方法,并在调用父类的初始化方法之后创buildbutton
在@ agy的答案是封闭的是不必要的,你可以做(在Swift 3):
lazy var button:UIBarButtonItem = UIBarButtonItem(title: "Title", style: .plain, target: self, action: #selector(buttonPressed(_:)))