// Immutable, and NSError must be Sendable because it conforms to Error in Swift openclassNSError : NSObject, NSCopying, NSSecureCoding, @uncheckedSendable {
/* Domain cannot be nil; dict may be nil if no userInfo desired. */ publicinit(domain: String, code: Int, userInfodict: [String : Any]?=nil) .... }
/// Retrieve the localized description for this error. publicvar localizedDescription: String { get } }
extensionNSError : Error { }
实际上这个协议没有任何内容,因此任意类、结构体、枚举都可以轻松实现Error协议。
定义Swift Error:
使用枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
enumNetworkError: Error { case domainError case decodingError case noDataError var localizedDescription: String { switchself { case .domainError: return"url错误" case .decodingError: return"解析出错" case .noDataError: return"无数据" } } }
由于错误一般是后台接口给出,所以个人觉得使用结构体表示错误,使用是最方便的:
1 2 3 4 5 6 7 8 9 10 11 12 13
structBusinessError: Error { var code ="" var message ="" init(code: String, message: String) { self.code = code self.message = message } var localizedDescription: String { return message } }