SwiftResult 提供了一个与 SE-0235 中提议的 Result
类型兼容的 Result
类型(关于修改的公告),该类型可能会在 Swift 5.x 中添加到 Swift 标准库中。使用它替换第三方 Result
类型可以更容易地将您的代码迁移到 Swift 5.x。
// An overload to return a `Result` instead of `throws`
extension JSONDecoder {
func decode<T: Decodable>(_ type: T.Type, from json: JSON) -> Result<T, DecodingError> {
...
}
}
let json: JSON = ...
let person: Result<Person, DecodingError> = JSONDecoder().decode(Person.self, from: json)
switch person {
case .success(let person):
... // Success
case .failure(let error):
... // Failure
}
let age: Result<Int, DecodingError> = person.map { $0.age }
do {
let age: Int = try age.get()
// Uses `age` here
} catch let error {
// Error handling
}
在您的 Package.swift 文件中的 dependencies
中添加以下内容。
.package(
url: "https://github.com/koher/SwiftResult.git",
from: "0.2.0"
)
github "koher/SwiftResult" ~> 0.2.0