以下是我的代码
如果URL载入成功,它将返回一个整数。网络连接不佳(例如需要登录才能访问互联网的机场)将不会返回整数,而是返回一个完整的HTML页面,要求登录。强制向下转换使用
当我编写此代码时,我认为它会运行catch语句,但实际上它返回了致命错误。如何捕获这个错误?
func contactForUpdates() -> Int {
//contact server for most recent version
let versionURL = settings.versionURL
if let url = URL(string: versionURL) {
do {
let contents = try NSString(contentsOf: url, usedEncoding: nil)
//NEXT LINE IS WHERE THE QUESTIONS LIES
return Int(contents as String)!
} catch {
// contents could not be loaded
processError("Current version could not be loaded.")
return Int(0)
}
} else {
// the URL was bad!
processError("Current version could not be loaded--URL was bad.")
return Int(0)
}
}
如果URL载入成功,它将返回一个整数。网络连接不佳(例如需要登录才能访问互联网的机场)将不会返回整数,而是返回一个完整的HTML页面,要求登录。强制向下转换使用
return Int(contents as String)!
将产生错误fatal error: unexpectedly found nil while unwrapping an Optional value
。当我编写此代码时,我认为它会运行catch语句,但实际上它返回了致命错误。如何捕获这个错误?