Skip to content

Instantly share code, notes, and snippets.

@ezura
Last active October 12, 2017 08:42
Show Gist options
  • Save ezura/bc44f070121457a239ced1932d36ffc8 to your computer and use it in GitHub Desktop.
Save ezura/bc44f070121457a239ced1932d36ffc8 to your computer and use it in GitHub Desktop.
lazy
public class Lazy<T> {
private let initializer: () -> T
private var _value: T!
public var value: T {
get {
// TODO: mutex
switch _value {
case .none:
_value = initializer()
return _value
case .some(let v):
return v
}
}
set {
_value = newValue
}
}
public init(initializer: @escaping () -> T) {
self.initializer = initializer
}
}
public func lazy<T>(initializer: @escaping () -> T) -> Lazy<T> {
return Lazy(initializer: initializer)
}
class B {
let v1 = lazy { return nil as Optional<A> } // self making
let v3 = lazy { () -> Int! in return 1 } // self making
lazy var v2 = { return A() }() // swift's `lazy`
}
let b = B()
b.v3.value = 2
b.v3.value // 2
b.v3.value = nil
b.v3.value // nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment