展开 nil 可选
Throwing on unwrapping nil optional
考虑以下代码:
enum MyErrorType:ErrorType {
case BadTimes
}
var mightHaveAValue: String?
do {
if let value = mightHaveAValue {
// do stuff with value
} else {
throw MyErrorType.BadTimes
}
// do stuff with NSFileManager using mightHaveAValue which might throw
} catch {
// handle error
}
...其中我有一个大 do/try/catch 块。在这种情况下,错误处理将是相同的,无论 mightHaveAValue
是空的还是稍后 NSFileManager
发生错误。所以重新使用错误处理代码是有意义的。
这是 Swift2 中最干净的方法吗,或者有什么方法可以自动 throw/catch 展开一个没有值的可选?
看起来不错,但使用 guard let
比 if let
更好,因为它允许您在主 do
块中使用未包装的值,而不必在if let
分支。您还可以使用多个 catch
分支来处理不同的错误类型。
do {
guard let value = mightHaveAValue else {
throw MyErrorType.BadTimes
}
// do stuff with value
} catch let error as MyErrorType {
// handle custom error
} catch let error as NSError {
// handle generic NSError
}
没有自动处理解包选项的方法,您必须使用许多已知方法之一:if let
、guard let
、nil coalescing 等
也许只使用这样的扩展程序
extension Optional {
func throwing() throws -> Wrapped {
if let wrapped = self {
return wrapped
} else {
throw NSError("Trying to access non existing value")
}
}
}
考虑以下代码:
enum MyErrorType:ErrorType {
case BadTimes
}
var mightHaveAValue: String?
do {
if let value = mightHaveAValue {
// do stuff with value
} else {
throw MyErrorType.BadTimes
}
// do stuff with NSFileManager using mightHaveAValue which might throw
} catch {
// handle error
}
...其中我有一个大 do/try/catch 块。在这种情况下,错误处理将是相同的,无论 mightHaveAValue
是空的还是稍后 NSFileManager
发生错误。所以重新使用错误处理代码是有意义的。
这是 Swift2 中最干净的方法吗,或者有什么方法可以自动 throw/catch 展开一个没有值的可选?
看起来不错,但使用 guard let
比 if let
更好,因为它允许您在主 do
块中使用未包装的值,而不必在if let
分支。您还可以使用多个 catch
分支来处理不同的错误类型。
do {
guard let value = mightHaveAValue else {
throw MyErrorType.BadTimes
}
// do stuff with value
} catch let error as MyErrorType {
// handle custom error
} catch let error as NSError {
// handle generic NSError
}
没有自动处理解包选项的方法,您必须使用许多已知方法之一:if let
、guard let
、nil coalescing 等
也许只使用这样的扩展程序
extension Optional {
func throwing() throws -> Wrapped {
if let wrapped = self {
return wrapped
} else {
throw NSError("Trying to access non existing value")
}
}
}