Last active
April 20, 2017 17:06
-
-
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...
This file contains 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
/// ¡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 | |
} |
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
Maybe "anidado" is a better term instead of "anillado"