Swift Result 类型
Result 类型是一个枚举,它包装成功和错误回调。
例如一个用户访问web API的场景。API可以异步返回结果(success state),也可以返回错误(failure state)。新的Result类型可以将结果包装为一个枚举类型,从而更容易访问这两种状态。
func fetchPosts(url: URL, completion: @escaping (Result<[Post],NetworkError>) -> Void) {
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
if let error = error as NSError?, error.domain == NSURLErrorDomain {
completion(.failure(.domainError))
}
return
}
do {
let posts = try JSONDecoder().decode([Post].self, from: data)
completion(.success(posts))
} catch {
completion(.failure(.decodingError))
}
}.resume()
}
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
fetchPosts(url: url) { result in
switch result {
case .success(let posts):
print(posts)
case .failure:
print("FAILED")
}
}
发表回复