Skip to content
A PoC of an ideal error handling in Swift
Swift C++ Makefile
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
SwiftEither.xcodeproj
SwiftEither
SwiftEitherTests
.gitignore
.travis.yml
Makefile
README.md

README.md

SwiftEither Build Status

An Either pattern implementation in Swift

SYNOPSIS

import SwiftEither

// helpers

struct Error {
    var reason: String
    init(_ reason: String) { self.reason = reason }
}

func success(s: String) -> Either<String, Error> {
    return Either(success: s)
}
func failure(s: String) -> Either<String, Error> {
    return Either(failure: Error(s))
}

// 1. basic use
let x = success("foo")
// x represents either success:String or failure:Error
switch x {
case .Success(let s):
    println(s.value) // "foo"
case .Failure(let f):
    println(f.value.reason) // not reached
}

// 2. Either chaining, just like to optional chaining
success("success").chain({ (m) -> Either<String, Error> in
    return success("chained")
}) // "chained"

failure("error!").chain({ (m) -> Either<String, Error> in
    return Either(success: "chained")
}) // "error!"

// 3. Fallback operation, just like to null coalescing operator
success("success").fallback({
    return success("chained")
}) // "success"

failure("error!").fallback({
    return success("fallback")
}) // "fallback"

// fallback operator
failure("error!") ?? success("fallback") // Either(success:"fallback")
failure("error!") ?? "fallback" // Either(success:"fallback")

DESCRIPTION

This is a proof-of-concept of an ideal error handling in Swift.

AUTHOR

Fuji, Goro (gfx) gfuji@cpan.org

LICENSE

The Apache 2.0 License

You can’t perform that action at this time.