Skip to content

Instantly share code, notes, and snippets.

@qmchenry
Last active April 18, 2016 18:37
Show Gist options
  • Save qmchenry/5020be8d12b9f65c60bfe1a85d201715 to your computer and use it in GitHub Desktop.
Save qmchenry/5020be8d12b9f65c60bfe1a85d201715 to your computer and use it in GitHub Desktop.
Lightweight generic cache
//
// 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
}
}
}
@qmchenry
Copy link
Author

// playgrounds are for playing! Paste the class above and these lines to try it out

var index = 1

func hashtagGenerator() -> String {
    index += 1
    return "#swift4eva \(index)"
}

let hashtagCache = ThinCache(generator: hashtagGenerator)

hashtagCache.value
hashtagCache.invalidate()
hashtagCache.generate()

let closureCache = ThinCache{ return "superthin \(index)" }
closureCache.value
index += 1
closureCache.value
closureCache.invalidate()
closureCache.value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment