Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active July 5, 2017 03:41
Show Gist options
  • Save ha1f/6c152828c7131590621d2ea4e3fb6797 to your computer and use it in GitHub Desktop.
Save ha1f/6c152828c7131590621d2ea4e3fb6797 to your computer and use it in GitHub Desktop.
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