采用 ??运算符并投入 Swift
Use ?? operator and throw in Swift
我不能在 Swift 3.
中写这个
let x = dict["key"] ?? throw SomeError()
它不编译。 (我目前正在使用 Xcode 8 beta 4。)我想那是因为 throw SomeError()
不被视为表达式?
正如您可能猜到的那样,我正在尝试将 x
设置为该值,如果不存在则抛出。执行此操作的最简单语法是什么?
您可以使用guard
statement
guard let x = dict["key"] else {
throw SomeError()
}
// now you can use x and sure it is not nil
print(x)
我不能在 Swift 3.
中写这个let x = dict["key"] ?? throw SomeError()
它不编译。 (我目前正在使用 Xcode 8 beta 4。)我想那是因为 throw SomeError()
不被视为表达式?
正如您可能猜到的那样,我正在尝试将 x
设置为该值,如果不存在则抛出。执行此操作的最简单语法是什么?
您可以使用guard
statement
guard let x = dict["key"] else {
throw SomeError()
}
// now you can use x and sure it is not nil
print(x)