在Swift 2.0中,如果我执行以下操作:
panel.beginSheetModalForWindow(self.view.window!) { (result) in
switch result {
// Save was selected
case NSFileHandlingPanelOKButton:
self.writeFile(fileString, fileURL: panel.URL!)
// something else was selected
default:
break
}
}
使用以下功能,它可以编译和工作。
func writeFile(fileString: String, fileURL: NSURL) {
do {
try fileString.writeToURL(fileURL, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
fatalError("Error writing to file - \(error)")
}
}
但是,如果我将这两者结合起来:
panel.beginSheetModalForWindow(self.view.window!) { (result) in
switch result {
// Save was selected
case NSFileHandlingPanelOKButton:
do {
try fileString.writeToURL(fileURL, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
fatalError("Error writing to file - \(error)")
}
// something else was selected
default:
break
}
}
它不会编译。我收到编译错误:
投掷类型'()投掷功能的转换无效 - > '到非投掷函数类型'(Int) - >空隙'
为什么?
答案 0 :(得分:1)
添加默认的catch块,如下所示:
[SentiSynset('decelerate.v.01'), SentiSynset('slow.v.02'), \
SentiSynset('slow.v.03'), SentiSynset('slow.a.01'),SentiSynset('slow.a.02'), \
SentiSynset('slow.a.04'), SentiSynset('slowly.r.01'),SentiSynset('behind.r.03')]
http://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch
答案 1 :(得分:0)
我发现了答案(在新的Apple开发者论坛上)。
如果你这样做,它可以工作:
panel.beginSheetModalForWindow(self.view.window!) { (result) in
switch result {
case NSFileHandlingPanelOKButton:
// Save was selected
do {
try fileString.writeToURL(panel.URL!, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
fatalError("Error writing to file : \(error)")
} catch {
fatalError("Error")
}
default:
// something else was selected
break
}
}
问题是“捕获”并非详尽无遗,导致投掷传播到封闭函数(不会“抛出”)。