Skip to content

Instantly share code, notes, and snippets.

@russbishop
Last active October 2, 2016 00:50
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 russbishop/63c1cdb65da7fa84bf8f to your computer and use it in GitHub Desktop.
Save russbishop/63c1cdb65da7fa84bf8f to your computer and use it in GitHub Desktop.
Flatten a Type?? -> Type? in Swift
// Russ Bishop
// PlanGrid
// MIT licensed, use freely.
public protocol OptionalType {
associatedtype WrappedType
init()
}
extension Optional: OptionalType {
public typealias WrappedType = Wrapped
public init() {
self = nil
}
}
public extension Optional where Wrapped: OptionalType {
func flatten() -> WrappedType {
switch self {
case .some(let value):
return value
case .none:
return WrappedType()
}
}
}
public extension Optional {
/// Applies a function to `Wrapped` if not `nil`
func apply(_ f: (Wrapped) -> Void) {
_ = self.map(f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment