nghialv / Try

Swift µframework providing Try<T>

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Try

Language [Carthage compatible] (https://github.com/Carthage/Carthage) License Issues

Swift µframework providing Try<T>.

This library is inspired by the Try implementation in Scala.

Without Try
enum FileError: ErrorType {
	case FileNotFound
	case Unknown
}
	
func lineCountOfFile(filename: String) throws -> Int {
	if exists(filename) {
		let file = open(filename)
		return file.lineCount
	} else {
		throw FileError.FileNotFound
	}
}
	
// traditional way with Swift 2.0
do {
	let lineCount = try lineCountOfFile("data.text")
	// do something
} catch {
	// error handling
}
 
Code with Try
let t = Try(try lineCountOfFile("data.text"))

switch t {
 	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
  • map <^>
let t = Try(try lineCountOfFile("data.text")).map { $0 * 5 }

switch t {
	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
  • flatMap >>-
let t = Try(try lineCountOfFile("data.text")).flapMap { Try(try doSomething($0)) }

switch t {
 	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
  • Operators
let t = Try(try lineCountOfFile("data.text")) <^> { $0 * 5} >>- { Try(try doSomething($0)) }

switch t {
	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}

Installation

  • Using Carthage
  • Insert github "nghialv/Try" to your Cartfile
  • Run carthage update
  • Using Cocoapods
  • Insert use_frameworks! to your Podfile
  • Insert pod "Try" to your Podfile
  • Run pod install
  • Using Submodule

Requirements

  • Swift 2.0 (Xcode 7.0 or later)
  • iOS 8.0 or later

About

Swift µframework providing Try<T>

License:MIT License


Languages

Language:Swift 81.9%Language:Ruby 10.0%Language:C++ 8.1%