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

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

问题描述

为什么要创建隐式展开的可选"而不是仅创建常规变量或常量? 如果您知道可以成功解包,那么为什么首先要创建一个可选的? 例如,为什么这样:

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"

变得比以下更有用:

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?

推荐答案

考虑一个对象的情况,该对象在构造和配置时可能具有nil属性,但是此后是不可变的且非nil(通常以这种方式对待NSImage ,尽管有时它仍然有用).隐式解开的可选对象将清理其代码,并且安全损失相对较低(只要持有一个保证,它将是安全的).

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.

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

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