Guest User

Untitled

a guest
Jun 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. //
  2. // CachedValue.swift
  3. //
  4. // Created by Chris Martin on 6/18/18.
  5. //
  6.  
  7. import Foundation
  8.  
  9. class CachedValue<Element> {
  10.  
  11. typealias ElementCreator = () -> Element
  12. private let creator: ElementCreator
  13.  
  14. private var cachedValue: Element?
  15.  
  16. public var value: Element {
  17.  
  18. if let value = cachedValue {
  19. return value
  20. }
  21. else {
  22. let value = creator()
  23. cachedValue = value
  24. return value
  25. }
  26. }
  27.  
  28. public init(creator: @escaping ElementCreator) {
  29.  
  30. self.creator = creator
  31. }
  32.  
  33. public func invalidate() {
  34.  
  35. cachedValue = nil
  36. }
  37. }
Add Comment
Please, Sign In to add comment