Skip to content

Instantly share code, notes, and snippets.

@ChrisBuchholz
Last active January 6, 2017 14:32
Show Gist options
  • Save ChrisBuchholz/473be0bd545c8c5edd5cd3232e045e40 to your computer and use it in GitHub Desktop.
Save ChrisBuchholz/473be0bd545c8c5edd5cd3232e045e40 to your computer and use it in GitHub Desktop.
swift and rust error handling
// run with `cargo script errors.rs`
#[derive(Debug)]
pub enum AError {
SomeError,
}
pub enum Ado {
A,
B,
}
pub fn a(ado: Ado) -> Result<String, AError> {
match ado {
Ado::A => Err(AError::SomeError),
Ado::B => Ok("Test".to_string()),
}
}
pub fn b(ado: Ado) -> Result<String, AError> {
let s = a(ado)?;
Ok(format!("got success `{}`", s))
}
fn main() {
println!("{:?}", b(Ado::A)); // outputs Err(SomeError)
println!("{:?}", b(Ado::B)); // outputs Ok("got success `Test`")
}
// run with `cat lib.swift errors.swift | swift -`
public enum AError: Error {
case SomeError
}
public enum Ado {
case A, B
}
public func a(_ ado: Ado) throws -> String {
switch ado {
case .A: throw AError.SomeError
case .B: return "Test"
}
}
public func b(_ ado: Ado) throws -> String {
let s = try a(ado)
return "got success `\(s)`"
}
print(try b(Ado.A)^) // output Err(main.AError.SomeError)
print(try b(Ado.B)^) // output Ok("got success `Test`")
// boilerplate Result type and the try-lift ^^ operator for errors.swift
public enum Result<T> {
case Ok(T)
case Err(Error)
}
postfix operator ^
postfix func ^<T>(_ c: @autoclosure () throws -> T) -> Result<T> {
do {
return .Ok(try c())
} catch {
return .Err(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment