Swift中的两个(或更多)选项 [英] Two (or more) optionals in Swift
问题描述
在观看Apple关于LLDB调试器的视频时,我发现了一些我无法找到解释的内容;当他写道时,他正在讨论可选值:
While watching an Apple's video about LLDB debugger I found something I can't find an explanation for; he was talking about optional values when he wrote:
var optional: String? = nil; //This is ok, a common optional
var twice_optional: String?? = nil; //What is this and why's this useful??
我开了一个游乐场并开始试用它并意识到你可以写多少?
如你所愿,然后使用相同数量的!
打开它们。我理解包装/展开变量的概念,但想不到我想要包装4,5或6次值的情况。
I opened a playground and started trying it out and realized that you can write as many as ?
as you want, and then unwrap them with the same number of !
. I understand the concept of wrapping/unwrapping a variable but can't think of a situation where I would like to wrap a value 4, 5 or 6 times.
推荐答案
(更新为Swift> = 3)
双选项可以很有用,Swift博客文章Optionals案例研究:valuesForKeys描述了一个应用程序。
"Double optionals" can be useful, and the Swift blog entry "Optionals Case Study: valuesForKeys" describes an application.
这是一个简化的例子:
let dict : [String : String?] = ["a" : "foo" , "b" : nil]
是一个带有可选字符串作为值的字典。因此
is a dictionary with optional strings as values. Therefore
let val = dict[key]
的类型为 String ??
aka 可选< Optional< String>>
。它是 .none
(或 nil
)
如果字典中没有该键,并且 .some(x)
否则。在第二个
的情况下, x
是一个字符串?
又名可选< String> ;
,可以是 .none
(或 nil
)
或 .some(s)
其中 s
是一个字符串。
has the type String??
aka Optional<Optional<String>>
. It is .none
(or nil
)
if the key is not present in the dictionary, and .some(x)
otherwise. In the second
case, x
is a String?
aka Optional<String>
and can be .none
(or nil
)
or .some(s)
where s
is a String.
您可以使用嵌套的可选绑定来检查各种情况:
You can use nested optional binding to check for the various cases:
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-statement中使用模式匹配
可以获得同样的结果可能是有益的:
It might be instructive to see how the same can be achieved with pattern matching in a switch-statement:
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")
}
(我不知道更深层嵌套的选项的合理应用。)
(I do not know a sensible application for more deeply nested optionals.)
这篇关于Swift中的两个(或更多)选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!