SwiftResult provides a Result
type which is compatible with the Result
type proposed in SE-0235 (announcement about modifications), which may be added to the Swift standard library in Swift 5.x. Replacing third-party Result
types with it may make it easier to migrate your code to 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
}
Add the following to dependencies
in your Package.swift.
.package(
url: "https://github.com/koher/SwiftResult.git",
from: "0.2.0"
)
github "koher/SwiftResult" ~> 0.2.0
Apache License. It follows Swift's license and Swift Evolution's license.