Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active Jul 5, 2017
Embed
What would you like to do?
Optional.swift
import Foundation
enum Optional<T> {
case none
case some(T)
init() {
self = .none
}
init(_ value: T) {
self = .some(value)
}
enum OptionalError: LocalizedError {
case unwrapNone
case general
var errorDescription: String? {
switch self {
case .unwrapNone:
return "Found nil while unwrapping optional value"
case .general:
return "Unknown optional error occured"
}
}
}
func value() throws -> T {
switch self {
case .none:
throw OptionalError.unwrapNone
case .some(let value):
return value
}
}
func map<R>(_ p: (T) -> R) -> Optional<R> {
switch self {
case .none:
return Optional<R>.none
case .some(let value):
return Optional<R>.some(p(value))
}
}
func flatMap<R>(_ p: (T) -> Optional<R>) -> Optional<R> {
switch self {
case .none:
return Optional<R>.none
case .some(let value):
switch p(value) {
case .none:
return Optional<R>.none
case .some(let value):
return Optional<R>.some(value)
}
}
}
}
// force-unwrap
// We can't declare `!` because of duplication
postfix operator *!
postfix func *!<T>(lhs: Optional<T>) -> T {
return try! lhs.value()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment