Swift - Lazy loading a property that can be made nil later

邮差的信 提交于 2019-12-03 21:37:24

The piece that you're missing is that, in Objective-C, it's creating the _navController ivar and setter for you; in Swfit you need to create those yourself.

Once you have those in place, your navController property in Swift can look pretty similar to the Objective-C one:

private var _navController: UINavigationController? = nil

var navController: UINavigationController! {
    get {
        if _navController == nil {
            let tempStoryboard = UIStoryboard(name: "Image", bundle: nil);
            _navController = tempStoryboard.instantiateInitialViewController() as? UINavigationController
        }

        return _navController
    }
    set {
        _navController = newValue
    }
}

Note: I delcared navController as an implicitly unwrapped UINavigationController so that it can be set to nil while still making it accessible without unwrapping the value every time. While using an implicitly unwrapped type can be dangerous, it's ok (and appropriate) to use in this case. Since we check for nil in the getter itself, we can guarantee that it will always return a non-nil value. Additionally, even though we're using a conditional downcast on the value returned from instantiateInitialViewController, we can say that any value returned from that function that is not a UINavigationController would be a programmer error and the resulting crash would be appropriate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!