0%

Swift中的Error

OC中的错误是一个类NSError:

1
2
3
4
5
6
7
8
9
// Immutable, and NSError must be Sendable because it conforms to Error in Swift
open class NSError : NSObject, NSCopying, NSSecureCoding, @unchecked Sendable {


/* Domain cannot be nil; dict may be nil if no userInfo desired.
*/
public init(domain: String, code: Int, userInfo dict: [String : Any]? = nil)
....
}

而Swift中的错误则是一个协议Error:

1
2
3
4
5
6
7
8
9
10
11
12
13
public protocol Error : Sendable {
}
public protocol Sendable {
}

extension Error {

/// Retrieve the localized description for this error.
public var localizedDescription: String { get }
}

extension NSError : Error {
}

实际上这个协议没有任何内容,因此任意类、结构体、枚举都可以轻松实现Error协议。

定义Swift Error:

使用枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum NetworkError: Error {
case domainError
case decodingError
case noDataError

var localizedDescription: String {
switch self {
case .domainError:
return "url错误"
case .decodingError:
return "解析出错"
case .noDataError:
return "无数据"
}
}
}

由于错误一般是后台接口给出,所以个人觉得使用结构体表示错误,使用是最方便的:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct BusinessError: Error {
var code = ""
var message = ""

init(code: String, message: String) {
self.code = code
self.message = message
}

var localizedDescription: String {
return message
}
}

如果需要具体判断错误码,可以扩展BusinessError,不同的业务接口可以创建不同的扩展。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extension BusinessError {
struct SuperLike {
static let unknow = ""
static let badParam = "-10000"
static let badGender = "-10001"
static let notMatch = "-10002"
static let overFrequent = "-10003"
}
}

func estimateErr() {
if error.code == BusinessError.SuperLike.badParam {
print("badParam")
} else if error.code == BusinessError.SuperLike.badGender {
print("badGender")
}
}
觉得文章有帮助可以打赏一下哦!