gpt4 book ai didi

ios - 在 Swift 中,如果你解开一个 "Implicitly Unwrapped Optional",这是一个双重解包吗?

转载 作者:行者123 更新时间:2023-11-28 13:18:56 26 4
gpt4 key购买 nike

我正在研究 !和 ?在 var 声明中。

我的问题简述

If you call unwrap! on a a var declared with ! - why isnt this a double unwrap?

我创建了两个 IBOutlets,因为这是什么时候!被大量使用

@IBOutlet weak var searchBar1: UISearchBar? //"Optional"
@IBOutlet weak var searchBar2: UISearchBar! //"Implicitly Unwrapped Optional"

我知道如果 outlets 不是 nil 那么所有这些都会起作用

self.searchBar1!.text = "dd" //builds ok but crashes on nil
self.searchBar2!.text = "dd" //builds ok but crashes on nil

self.searchBar1?.text = "dd1" //builds ok but does nothing on nil
self.searchBar2?.text = "dd1" //builds ok but does nothing on nil

//---
self.searchBar1.text = "dd2" //ERROR: 'UISearchBar?' does not have a member named 'text'
self.searchBar1!.text = "dd2" //OK: must unwrap Optional(UISearchBar) to UISearchBar
self.searchBar1!.text = "dd2" //OK: must unwrap Optional(UISearchBar) to UISearchBar

self.searchBar2.text = "dd2" //ok unwrap declared in var but will crash if nil
//----

我认为最后一行有效是正确的吗,因为解包在 var 声明中

之所以可行,是因为 Unwrap!在 var 声明中

self.searchBar2.text = "dd2" 

为什么不崩溃——这不是双重解包

self.searchBar2!.text = "dd" 

self.searchBar 是可选的(UISearchBar)>> 打开! self.searchBar2! >> UISearchBar

最佳答案

the book中的两个关键句是:

An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a nonoptional value, without the need to unwrap the optional value each time it is accessed.

You can think of an implicitly unwrapped optional as giving permission for the optional to be unwrapped automatically whenever it is used.

我的理解是,隐式解包的可选项就像普通的可选项一样,可以像一个一样访问,包括使用解包!运营商就可以了。隐式解包只是消除了需要解包,而不是在您不这样做时导致错误。

这是一个“普通的可选值……但可以像非可选值一样使用”——对我来说这意味着两种访问它的方法都很好。

关于ios - 在 Swift 中,如果你解开一个 "Implicitly Unwrapped Optional",这是一个双重解包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com