为什么要创建“Implicitly Unwrapped Optionals",因为这意味着您知道存在价值? [英] Why create "Implicitly Unwrapped Optionals", since that implies you know there's a value?

查看:38
本文介绍了为什么要创建“Implicitly Unwrapped Optionals",因为这意味着您知道存在价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 an optional in the first place? For example, why is this:

let someString: String! = "this is the string"

going to be more useful than:

let someString: String = "this is the string"

If "optionals indicate that a constant or variable is allowed to have 'no value'", but "sometimes it is clear from a program’s structure that an optional will always have a value after that value is first set", what is the point of making it an optional in the first place? If you know an optional is always going to have a value, doesn't that make it not optional?

解决方案

Consider the case of an object that may have nil properties while it's being constructed and configured, but is immutable and non-nil afterwards (NSImage is often treated this way, though in its case it's still useful to mutate sometimes). Implicitly unwrapped optionals would clean up its code a good deal, with relatively low loss of safety (as long as the one guarantee held, it would be safe).

(Edit) To be clear though: regular optionals are nearly always preferable.

这篇关于为什么要创建“Implicitly Unwrapped Optionals",因为这意味着您知道存在价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆