相关疑难解决方法(0)

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

在观看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次的情况.

optional ios swift

15
推荐指数
1
解决办法
1126
查看次数

如何与合并运算符一起使用try?

我正在尝试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)

如果我更改trytry?

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 …

swift

5
推荐指数
1
解决办法
288
查看次数

在 try 中使用零合并运算符?for 抛出并返回可选值的函数

我想在以下两种情况下使用 nil-coalescing 运算符设置默认值:

  1. 函数抛出错误
  2. 函数返回 nil

请看一下下面的代码片段。我有以下问题:

  1. 为什么 item1 为零?
  2. item1 和 item2 的初始化有什么区别
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)

error-handling swift option-type

4
推荐指数
1
解决办法
557
查看次数

标签 统计

swift ×3

error-handling ×1

ios ×1

option-type ×1

optional ×1