Skip to content

Instantly share code, notes, and snippets.

@NinoScript
Last active March 9, 2017 16:48
Show Gist options
  • Select an option

  • Save NinoScript/f316a8f40992fb2fe521694f68b8601b to your computer and use it in GitHub Desktop.

Select an option

Save NinoScript/f316a8f40992fb2fe521694f68b8601b to your computer and use it in GitHub Desktop.

Revisions

  1. NinoScript revised this gist Mar 9, 2017. 1 changed file with 10 additions and 12 deletions.
    22 changes: 10 additions & 12 deletions ThrowingUtils.swift
    Original file line number Diff line number Diff line change
    @@ -5,10 +5,7 @@
    // WTFPLv2
    //

    import Foundation

    // Usage example: try maybeValue.unwrapped()
    struct UnwrappingError: Error {}
    extension Optional {
    func unwrapped() throws -> Wrapped {
    guard let unwrapped = self else {
    @@ -17,17 +14,9 @@ extension Optional {
    return unwrapped
    }
    }
    struct UnwrappingError: Error {}

    // 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(
    @@ -38,3 +27,12 @@ func cast<T, U> (_ input: T) throws -> U {
    }
    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)"
    }
    }
  2. NinoScript created this gist Mar 9, 2017.
    40 changes: 40 additions & 0 deletions ThrowingUtils.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    //
    // 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
    }