gpt4 book ai didi

Swift 2 if let with do-try-catch

转载 作者:IT王子 更新时间:2023-10-29 05:21:07 25 4
gpt4 key购买 nike

在 Swift 1.2 中我有这个:

if let filePath = NSBundle.mainBundle().pathForResource("some", ofType: "txt"),
data = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) {
for line in data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) {
// Do something
}
} else {
println("some.txt is missing")
}

在 Swift 2 中,我不能再这样做了,因为 pathForResourcecontentsOfFile 都可以抛出,也可以返回可选值。我可以修复它,但它现在看起来非常冗长:

do {
if let filePath = try NSBundle.... {
do {
if let data = try String.... {
for line in data..... {
// Do something
}
} else {
print("Nil data")
}
} catch {
print("contentsOfFile threw")
}
} else {
print("Nil pathForResource")
}
} catch {
print("pathForResource threw")
}

我想我错过了一些东西 - 感谢您的帮助。

最佳答案

使用 guard 语法代替 if-let。

这是一个示例:

do {

guard let filePath = try NSBundle .... else {
// if there is exception or there is no value
throw SomeError
}
guard let data = try String .... else {
}

} catch {

}

if-let 和 guard 的区别在于展开值的范围。如果您使用 if-let filePath 值仅在 if-let block 内可用。如果您使用保护文件路径值可用于保护调用的范围。

这是swift book中的相关部分

A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else` clause is executed if the condition is not true.

关于Swift 2 if let with do-try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com