YetAnotherResult 1.2.12

YetAnotherResult 1.2.12

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Feb 2016
SPMSupports SPM

Maintained by Mikhail Stepkin, Mikhail Stepkin.



  • By
  • Mikhail Stepkin

Result

Simple Swift μ-framework that wraps your throwing functions results.

How to install

Swift package manager

Package.swift:

import PackageDescription

let package = Package(
  …
  dependencies: [
    …
    .Package(url: "https://github.com/Skogetroll/Result.git", majorVersion: 1, minor: 2),
    …
  ]
  …
)

How to use?

Like this:

let result = Result<Type> {
    // Your unsafe code resulting in Type or Error goes here
}

or like this:

let result = Result<Type>(/* Your unsafe code resulting in Type or Error goes here */)

How to get value?

let value: Type? = result.value

How to get error?

let error: ErrorType? = result.error

How to crash application return back to throwing paradigm?

let value: Type = try result.unwrap()

What else can I do with Result<V>?

You can use

Map:

let resultString = Result<String>(try unsafelyGetString())
let stringLength = resultString.map { string in
  string.characters.count
}

// stringLength now contains either value of `String.Index.Distance` or error wrapped in Result<Distance>

// Or you can use operator `<^>` to perform map
process <^> resultString
// Here `process : String -> Void` gonna be called if and only if resultString resulted successfully

Flat map:

let someResult = Result(try unsafelyGetResult())
let processedResult = someResult.flatMap { value in
    return Result(try someUnsafeProcessing(value))
}

// or you can use operators `>>-` and `-<<`

let processedResult = someResult >>- { value in Result(try someUnsafeProcessing(value)) }

Apply:

let resultedFunction: Result<A -> B> =let resultedValue: A =let result: Result<B> = resultedValue.apply(resultedFunction)

// or you can use operator `<*>`

let result: Result<B> = resultedFunction <*> resultedValue

Wrap:

func yourThrowingFunction(in: InType) throws -> (out: OutType) {
    …
}

let resultWrappedFunction: InType -> Result<OutType> = wrap(yourThrowingFunction)

let someInput: InType =// And we can get
let resultOutput = resultWrappedFunction(someInput)

// instead of
do {
    let output = try yourThrowingFunction(someInput)
}