Last active
October 2, 2016 00:50
-
-
Save russbishop/63c1cdb65da7fa84bf8f to your computer and use it in GitHub Desktop.
Flatten a Type?? -> Type? in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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