協議
Error
表示可以拋出的錯誤值的類型。
聲明
protocol Error : Sendable
概述
任何聲明符合 Error
協議的類型都可以用來表示 Swift 錯誤處理係統中的錯誤。因為Error
協議沒有自己的要求,所以您可以聲明與您創建的任何自定義類型的一致性。
使用枚舉作為錯誤
Swift 的枚舉非常適合表示簡單的錯誤。創建一個符合 Error
協議的枚舉,並為每個可能的錯誤提供一個案例。如果有可能有助於恢複的有關錯誤的其他詳細信息,請使用關聯值來包含該信息。
以下示例顯示了 IntParsingError
枚舉,該枚舉捕獲在從字符串解析整數時可能發生的兩種不同類型的錯誤:溢出,其中字符串表示的值對於整數數據類型來說太大,以及無效輸入,其中在輸入中找到非數字字符。
enum IntParsingError: Error {
case overflow
case invalidInput(Character)
}
invalidInput
case 包含無效字符作為關聯值。
下一個代碼示例顯示了 Int
類型的可能擴展,它解析 String
實例的整數值,在解析過程中出現問題時拋出錯誤。
extension Int {
init(validating input: String) throws {
// ...
let c = _nextCharacter(from: input)
if !_isValid(c) {
throw IntParsingError.invalidInput(c)
}
// ...
}
}
在 do
語句中調用新的 Int
初始化程序時,您可以使用模式匹配來匹配自定義錯誤類型的特定情況並訪問它們的關聯值,如下例所示。
do {
let price = try Int(validating: "$100")
} catch IntParsingError.invalidInput(let invalid) {
print("Invalid character: '\(invalid)'")
} catch IntParsingError.overflow {
print("Overflow error")
} catch {
print("Other error")
}
// Prints "Invalid character: '$'"
在錯誤中包含更多數據
有時您可能希望不同的錯誤狀態包含相同的公共數據,例如文件中的位置或應用程序的某些狀態。當你這樣做時,使用一個結構來表示錯誤。以下示例在解析 XML 文檔時使用結構來表示錯誤,包括發生錯誤的行號和列號:
struct XMLParsingError: Error {
enum ErrorKind {
case invalidCharacter
case mismatchedTag
case internalError
}
let line: Int
let column: Int
let kind: ErrorKind
}
func parse(_ source: String) throws -> XMLDoc {
// ...
throw XMLParsingError(line: 19, column: 5, kind: .mismatchedTag)
// ...
}
再一次,使用模式匹配來有條件地捕獲錯誤。以下是捕獲 parse(_:)
函數拋出的任何 XMLParsingError
錯誤的方法:
do {
let xmlDoc = try parse(myXMLData)
} catch let e as XMLParsingError {
print("Parsing error: \(e.kind) [\(e.line):\(e.column)]")
} catch {
print("Other error: \(error)")
}
// Prints "Parsing error: mismatchedTag [19:5]"
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift EnumeratedSequence forEach(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator map(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator flatMap(_:)用法及代碼示例
- Swift EmptyCollection first(where:)用法及代碼示例
- Swift ExpressibleByIntegerLiteral用法及代碼示例
- Swift EmptyCollection index(_:offsetBy:limitedBy:)用法及代碼示例
- Swift EnumeratedSequence drop(while:)用法及代碼示例
- Swift EmptyCollection partition(by:)用法及代碼示例
- Swift EnumeratedSequence.Iterator allSatisfy(_:)用法及代碼示例
- Swift ExpressibleByStringInterpolation init(stringInterpolation:)用法及代碼示例
- Swift EmptyCollection prefix(upTo:)用法及代碼示例
- Swift EmptyCollection starts(with:)用法及代碼示例
- Swift EnumeratedSequence用法及代碼示例
- Swift EmptyCollection.Iterator split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift EmptyCollection.Iterator starts(with:)用法及代碼示例
- Swift EnumeratedSequence.Iterator drop(while:)用法及代碼示例
- Swift EmptyCollection.Iterator prefix(_:)用法及代碼示例
- Swift EmptyCollection sorted(by:)用法及代碼示例
- Swift EmptyCollection dropFirst(_:)用法及代碼示例
- Swift EnumeratedSequence dropFirst(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator filter(_:)用法及代碼示例
- Swift EmptyCollection enumerated()用法及代碼示例
- Swift EmptyCollection sort()用法及代碼示例
- Swift EnumeratedSequence.Iterator reduce(into:_:)用法及代碼示例
- Swift EnumeratedSequence compactMap(_:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Error。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。