result
The result is a Swift library that provides a set of utility functions for working with results in a more ergonomic way.
Installation
To install the result library, you can use either Cocoapods or Swift Package Manager.
Installation with Cocoapods
To install result using Cocoapods, add the following line to your Podfile:
pod 'Result'
Then, run the following command:
pod install
Installation with Swift Package Manager
To install the result library using Swift Package Manager, add the library as a dependency in your Package.swift file:
dependencies: [
.package(url: "https://github.com/antitypical/Result.git", from: "5.0.0")
]
Usage
The result library provides a Result
type that represents the result of a computation that may succeed or fail. It has two possible cases: success
and failure
.
Creating a Result
To create a Result
instance, you can use the following constructors:
Result.success(value: T)
– Creates a successful result with a given value.Result.failure(error: Error)
– Creates a failed result with a given error.
For example:
let successResult: Result<Int, Error> = .success(value: 42)
let failureResult: Result<Int, Error> = .failure(error: SomeError())
Extracting the Value
You can extract the value of a successful Result
using the get()
method:
let value = successResult.get()
If the result is a failure, the get()
method will throw an error.
Working with Result
You can perform various operations on a Result
instance using map, flatMap, and more, just like working with other monads.
For example:
func divide(a: Int, b: Int) -> Result<Int, Error> {
if b == 0 {
return .failure(error: DivisionError())
} else {
return .success(value: a / b)
}
}
let result = divide(a: 10, b: 2).map { $0 * 2 }
Contributing
If you want to contribute to the result library, please follow the guidelines in the CONTRIBUTING.md file.
License
The result library is released under the MIT License. For more information, see the LICENSE file.