- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 186字
- 2021-07-02 23:54:30
Error handling
Swift provides support to throw, catch, propagate, and manipulate recoverable errors at runtime.
Value types should conform to the Error protocol to be represented as errors. The following example presents some 4xx and 5xx HTTP errors as enum:
enum HttpError: Error {
case badRequest
case unauthorized
case forbidden
case requestTimeOut
case unsupportedMediaType
case internalServerError
case notImplemented
case badGateway
case serviceUnavailable
}
We will be able to throw errors using the throw keyword and mark functions that can throw errors with the throws keyword.
We can use a do-catch statement to handle errors by running a block of code. The following example presents JSON parsing error handling in a do-catch statement:
protocol HttpProtocol{
func didRecieveResults(results: Any)
}
struct WebServiceManager {
var delegate:HttpProtocol?
let data: Data
func test() {
do {
let jsonResult = try JSONSerialization.jsonObject(with:
self.data, options: JSONSerialization.ReadingOptions
.mutableContainers)
self.delegate?.didRecieveResults(results: jsonResult)
} catch let error {
print("json error" + error.localizedDescription)
}
}
}
We can use a defer statement to execute a set of statements just before code execution leaves the current code block, regardless of how the execution leaves the current block of code.
推薦閱讀
- 我們都是數據控:用大數據改變商業、生活和思維方式
- 文本數據挖掘:基于R語言
- UDK iOS Game Development Beginner's Guide
- 大數據架構和算法實現之路:電商系統的技術實戰
- 中國數字流域
- 大數據架構商業之路:從業務需求到技術方案
- 淘寶、天貓電商數據分析與挖掘實戰(第2版)
- Python數據分析與數據化運營
- 數據中心經營之道
- 數據中臺實戰:手把手教你搭建數據中臺
- Python金融數據挖掘與分析實戰
- SQL Server 2012 數據庫教程(第3版)
- 算力芯片:高性能CPU/GPU/NPU微架構分析
- 工業大數據分析實踐
- UnrealScript Game Programming Cookbook