-
-
Save ranmyfriend/dde42db5810eaabc17e6ddde68ae1a50 to your computer and use it in GitHub Desktop.
Tiny Result type in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Credit: Hooman Mehr via swift-evolution | |
// https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20171113/041314.html | |
import Foundation | |
public enum Result<Value> { | |
case success(Value) | |
case failure(Error) | |
public init(_ value: Value) { self = .success(value) } | |
public init(error: Error) { self = .failure(error) } | |
public init(_ expression: @autoclosure () throws -> Value) { | |
do { | |
self = .success(try expression()) | |
} | |
catch { | |
self = .failure(error) | |
} | |
} | |
public init(_ closure: () throws -> Value) { | |
do { | |
self = .success(try closure()) | |
} | |
catch { | |
self = .failure(error) | |
} | |
} | |
public func get() throws -> Value { | |
switch self { | |
case let .success(value): return value | |
case let .failure(error): throw error | |
} | |
} | |
public func map<U>(_ transform: (Value) throws -> U) throws -> U { | |
return try transform(get()) | |
} | |
public var value: Value? { | |
switch self { | |
case let .success(value): return value | |
case .failure: return nil | |
} | |
} | |
public var error: Error? { | |
switch self { | |
case .success: return nil | |
case let .failure(error): return error | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func doSomething() -> Result<String> { | |
return Result("Done!") | |
} | |
let result = doSomething() | |
do { | |
let value = try result.get() | |
print(value) | |
} | |
catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment