在观看Apple关于LLDB调试器的视频时,我发现了一些我无法找到解释的内容; 当他写道时,他正在谈论可选值:
var optional: String? = nil; //This is ok, a common optional
var twice_optional: String?? = nil; //What is this and why's this useful??
Run Code Online (Sandbox Code Playgroud)
我打开了一个游乐场并开始尝试它,并意识到你可以根据需要编写任意?数量的游戏,然后用相同的数量打开它们!.我理解包装/解包变量的概念,但不能想到我想要包装值4,5或6次的情况.
我正在尝试x从一个带有f一个参数(字符串)并抛出的函数分配一个值。
当前范围抛出了,所以我相信do... catch不是必需的。
我正在尝试try与合并运算符一起使用,??但出现此错误:'try' cannot appear to the right of a non-assignment operator。
guard let x = try f("a") ??
try f("b") ??
try f("c") else {
print("Couldn't get a valid value for x")
return
}
Run Code Online (Sandbox Code Playgroud)
如果我更改try为try?:
guard let x = try? f("a") ??
try? f("b") ??
try? f("c") else {
print("Couldn't get a valid value for x")
return
}
Run Code Online (Sandbox Code Playgroud)
我得到警告Left side …
我想在以下两种情况下使用 nil-coalescing 运算符设置默认值:
请看一下下面的代码片段。我有以下问题:
enum VendingMachineError: Error {
case invalidCode
}
class VendingMachine {
func itemCode(code: Int) throws -> String? {
guard code > 0 else {
throw VendingMachineError.invalidCode
}
if code == 1 {
return nil
} else {
return "Item #" + String(code)
}
}
}
let machine = VendingMachine()
// Question: Why is this nil?
let item1 = try? machine.itemCode(code: 0) ?? "Unknown"
print(item1)
// nil
// …Run Code Online (Sandbox Code Playgroud)