我在swift类中定义了一个getter。我想检查值是否为nil,如果是,则创建一个新实例;否则返回该值。我现在进入递归调用,因为我在getter方法中调用self.userHomeNvController。我喜欢我应该如何快速实现这一点。
var userHomeNavController:UINavigationController? {
get {
var ctr:UINavigationController? = self.userHomeNavController
if self.userHomeNavController == nil{
ctr = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeNavigationController") as? UINavigationController
}
return ctr
}
}
答案 0 :(得分:2)
使用通过运行闭包初始化的惰性属性:
lazy var userHomeNavController: UINavigationController? = {
let controller = self.storyboard?.instantiateViewControllerWithIdentifier("UserHomeNavigationController") as? UINavigationController
return controller
}()