gpt4 book ai didi

ios - Swift 中的两个(或更多)可选项

转载 作者:IT王子 更新时间:2023-10-29 05:19:22 26 4
gpt4 key购买 nike

在观看有关 LLDB 调试器的 Apple 视频时,我发现了一些我无法找到解释的内容;他写道:

var optional: String? = nil; //This is ok, a common optional
var twice_optional: String?? = nil; //What is this and why's this useful??

我打开了一个 playground 并开始尝试,发现你可以写多少个 ?,然后用相同数量的 ! 展开它们.我理解包装/展开变量的概念,但想不出我想要将值包装 4、5 或 6 次的情况。

最佳答案

(针对 Swift 更新 >=3)

“双重可选”可能很有用,Swift 博客条目 "Optionals Case Study: valuesForKeys"描述了一个应用程序。

这是一个简化的例子:

let dict : [String : String?] = ["a" : "foo" , "b" : nil]

是一个以可选字符串作为值的字典。因此

let val = dict[key]

具有类型 String??又名 Optional<Optional<String>> .是.none (或 nil )如果键不存在于字典中,并且 .some(x)否则。在第二案例,xString?又名 Optional<String>可以是.none (或 nil )或 .some(s)其中 s是一个字符串。

您可以使用嵌套的可选绑定(bind)来检查各种情况:

for key in ["a", "b", "c"] {

let val = dict[key]
if let x = val {
if let s = x {
print("\(key): \(s)")
} else {
print("\(key): nil")
}
} else {
print("\(key): not present")
}

}

输出:

a: foo
b: nil
c: not present

了解如何通过模式匹配实现同样的目标可能具有指导意义在 switch 语句中:

let val = dict[key]
switch val {
case .some(.some(let s)):
print("\(key): \(s)")
case .some(.none):
print("\(key): nil")
case .none:
print("\(key): not present")
}

或者,使用 x?模式作为 .some(x) 的同义词:

let val = dict[key]
switch val {
case let (s??):
print("\(key): \(s)")
case let (s?):
print("\(key): nil")
case nil:
print("\(key): not present")
}

(我不知道更深层嵌套的可选值的合理应用。)

关于ios - Swift 中的两个(或更多)可选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27225232/

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