Skip to content

Instantly share code, notes, and snippets.

@swiftyfinch
Created January 30, 2021 11:09
Show Gist options
  • Select an option

  • Save swiftyfinch/4ef47a636a485fc4e1610ea06629d6b2 to your computer and use it in GitHub Desktop.

Select an option

Save swiftyfinch/4ef47a636a485fc4e1610ea06629d6b2 to your computer and use it in GitHub Desktop.

Revisions

  1. swiftyfinch created this gist Jan 30, 2021.
    22 changes: 22 additions & 0 deletions Optional+Unwrap.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    protocol OptionalType {
    associatedtype Wrapped
    var optional: Wrapped? { get }
    }

    extension Optional: OptionalType {
    var optional: Self { self }
    }

    extension Optional {
    func unwrap(orThrow error: Error) throws -> Wrapped {
    guard let unwrapped = self else { throw error }
    return unwrapped
    }
    }

    extension Optional where Wrapped: OptionalType {
    func unwrap(orThrow error: Error) throws -> Wrapped.Wrapped {
    guard let unwrapped = self as? Wrapped.Wrapped else { throw error }
    return unwrapped
    }
    }