Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Created March 9, 2017 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NinoScript/75cd3701139821275e96d2272ab12ed9 to your computer and use it in GitHub Desktop.
Save NinoScript/75cd3701139821275e96d2272ab12ed9 to your computer and use it in GitHub Desktop.
Just some uti
//
// ThrowingUtils.swift
//
// Created by Cristián Arenas Ulloa on 1/13/17.
// WTFPLv2
//
import Foundation
// Usage example: try maybeValue.unwrapped()
struct UnwrappingError: Error {}
extension Optional {
func unwrapped() throws -> Wrapped {
guard let unwrapped = self else {
throw UnwrappingError()
}
return unwrapped
}
}
// Usage example: try cast(anyValue) as [String: Any]
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)"
}
}
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment