Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Last active March 9, 2017 16:48
Show Gist options
  • Save NinoScript/f316a8f40992fb2fe521694f68b8601b to your computer and use it in GitHub Desktop.
Save NinoScript/f316a8f40992fb2fe521694f68b8601b to your computer and use it in GitHub Desktop.
Just some utility functions for when you are working inside a throwing function
//
// ThrowingUtils.swift
//
// Created by Cristián Arenas Ulloa on 1/13/17.
// WTFPLv2
//
// Usage example: try maybeValue.unwrapped()
extension Optional {
func unwrapped() throws -> Wrapped {
guard let unwrapped = self else {
throw UnwrappingError()
}
return unwrapped
}
}
struct UnwrappingError: Error {}
// Usage example: try cast(anyValue) as [String: Any]
func cast<T, U> (_ input: T) throws -> U {
guard let output = input as? U else {
throw CastingError(
element: String(describing: type(of: input)),
from: String(describing: T.self),
to: String(describing: U.self)
)
}
return output
}
struct CastingError: Error {
let element: String
let from: String
let to: String
var localizedDescription: String {
return "CastingError: couldn't cast element of type \(element) from \(from) to \(to)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment