Last active
April 18, 2016 18:37
-
-
Save qmchenry/5020be8d12b9f65c60bfe1a85d201715 to your computer and use it in GitHub Desktop.
Lightweight generic cache
This file contains hidden or 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
// | |
// ThinCache.swift | |
// Planned | |
// | |
// Created by Quinn McHenry on 4/10/16. | |
// Copyright © 2016 Quinn McHenry. All rights reserved. | |
// | |
final class ThinCache<T> { | |
private var cached: Optional<T> | |
let generator: Void -> T | |
init(generator: Void -> T) { | |
self.generator = generator | |
} | |
func generate() -> T { | |
let t = generator() | |
cached = t | |
return t | |
} | |
func invalidate() { | |
cached = nil | |
} | |
var value: T { | |
get { | |
guard let cached = cached else { return generate() } | |
return cached | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
// playgrounds are for playing! Paste the class above and these lines to try it out