Skip to content

Instantly share code, notes, and snippets.

@colinator
Last active April 20, 2017 17:06
Show Gist options
  • Save colinator/d56ad40739d0d71eef911094fe85732e to your computer and use it in GitHub Desktop.
Save colinator/d56ad40739d0d71eef911094fe85732e to your computer and use it in GitHub Desktop.
LazyOptional variables can be nilled after the fact. Fun with operators! Having a spanish keyboard helps...
/// ¡Solo para el español!
/// Una clase que permite variables opcionales destructibles perezosas.
/// Mantiene el código de construcción cerca de la declaración variable
/// como perezoso, pero puede ser anidado a voluntad.
///
/// Para los gringos:
/// ¿ = option shift ?
/// ¡ = option 1
///
/// ejemplo:
///
/// let thingyView = LazyOptional<UIView> {
/// let k = UIView()
/// k.color = .blau
/// self.addSubview(k)
/// return k
/// }
/// if let view = thingyView¿ {
/// view.something = .whatever
/// }
/// thingyView¡.something = .whatever
/// thingyView¿.removeFromSuperview()
/// thingyView =! nil
/// thingyView¡.something = .whatever // will be constructed again
class LazyOptional<T> {
var value: T?
typealias ConstructorType = () -> T
private let constructor: ConstructorType
init(_ constructor: @escaping ConstructorType) {
self.constructor = constructor
}
private func ensure() {
if value == nil {
value = constructor()
}
}
var force: T {
ensure()
return value!
}
}
postfix operator ¿
postfix func ¿ <T>(lazyOptional: LazyOptional<T>) -> T? {
return lazyOptional.value
}
postfix operator ¡
postfix func ¡ <T>(lazyOptional: LazyOptional<T>) -> T {
return lazyOptional.force
}
infix operator =!
func =! <T>(lhs: LazyOptional<T>, rhs: T?) {
lhs.value = rhs
}
@billyto
Copy link

billyto commented Apr 20, 2017

Maybe "anidado" is a better term instead of "anillado"

@colinator
Copy link
Author

Fixed. That was google translate. I don't actually speak spanish ;)

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