Last active
October 12, 2017 08:42
-
-
Save ezura/bc44f070121457a239ced1932d36ffc8 to your computer and use it in GitHub Desktop.
lazy
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
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) | |
} |
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
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