Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1839
深忆病人
深忆病人 2020-11-22 07:30

Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 07:48

    One-line (or several-line) simple examples don't cover the behavior of optionals very well — yeah, if you declare a variable and provide it with a value right away, there's no point in an optional.

    The best case I've seen so far is setup that happens after object initialization, followed by use that's "guaranteed" to follow that setup, e.g. in a view controller:

    class MyViewController: UIViewController {
    
        var screenSize: CGSize?
    
        override func viewDidLoad {
            super.viewDidLoad()
            screenSize = view.frame.size
        }
    
        @IBAction printSize(sender: UIButton) {
            println("Screen size: \(screenSize!)")
        }
    }
    

    We know printSize will be called after the view is loaded — it's an action method hooked up to a control inside that view, and we made sure not to call it otherwise. So we can save ourselves some optional-checking/binding with the !. Swift can't recognize that guarantee (at least until Apple solves the halting problem), so you tell the compiler it exists.

    This breaks type safety to some degree, though. Anyplace you have an implicitly unwrapped optional is a place your app can crash if your "guarantee" doesn't always hold, so it's a feature to use sparingly. Besides, using ! all the time makes it sound like you're yelling, and nobody likes that.

提交回复
热议问题