Swift 3: 'if let' 可选绑定错误

Swift 3: 'if let' optional binding error

我在 Swift 3 工作,在进行以下 if let 测试时遇到问题:

let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")

if let plistData = try Data(contentsOf: plistUrl!) {
  ...some code
}

编译器在 if let 语句中显示以下错误:

Initializer for conditional binding must have Optional type, not 'Data'

这是什么问题,我该如何解决?

try 不是 return 可选的。 try? 确实如此。

使用 Swift,处理错误和从可能引发错误的方法中检索数据的正确方法在“Swift 编程语言”的 Error Handling 部分进行了说明。

因此,根据您的需要,您可以选择以下3种模式之一来解决您的问题。


1。使用 do-catchtry 关键字检索数据并处理错误

You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.

用法:

let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!

let plistData: Data?
do {
    plistData = try Data(contentsOf: plistUrl)
} catch {
    print(error as NSError)
    plistData = nil
}
    
print(plistData)

2。使用 try? 关键字

检索数据并将错误转换为可选值

You use try? to handle an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil.

用法:

let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!
    
guard let plistData = try? Data(contentsOf: plistUrl) else {
    return
}
    
print(plistData)

3。使用 try! 关键字

检索数据并禁用错误传播

Sometimes you know a throwing function or method won’t, in fact, throw an error at runtime. On those occasions, you can write try! before the expression to disable error propagation and wrap the call in a runtime assertion that no error will be thrown. If an error actually is thrown, you’ll get a runtime error.

用法:

let plistUrl = Bundle.main().urlForResource("Books", withExtension: "plist")!
    
let plistData = try! Data(contentsOf: plistUrl)
    
print(plistData)