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

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

问题描述

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

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天全站免登陆