Skip to content

Instantly share code, notes, and snippets.

@ollieatkinson
Created September 9, 2020 22:04
Show Gist options
  • Save ollieatkinson/94fda8d5c98999ba45deeb63cf8f2f8c to your computer and use it in GitHub Desktop.
Save ollieatkinson/94fda8d5c98999ba45deeb63cf8f2f8c to your computer and use it in GitHub Desktop.
Implementation of an Optional protocol for Swift using Swift 5.3 enum case as protocol witness
public protocol OptionalProtocol: ExpressibleByNilLiteral {
associatedtype Wrapped
var wrapped: Wrapped? { get }
static var none: Self { get }
static func some(_ newValue: Wrapped) -> Self
func map<U>(_ f: (Wrapped) throws -> U) rethrows -> U?
func flatMap<U>(_ f: (Wrapped) throws -> U?) rethrows -> U?
}
extension Optional: OptionalProtocol {
public var wrapped: Wrapped? { return self }
}
@ollieatkinson
Copy link
Author

Makes this kind of code possible:

extension Sequence where Element: OptionalProtocol {
     public func compacted() -> [Element.Wrapped] {
         compactMap(\.wrapped)
     }
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment