[swift-users] Lazily populated dictionary

Erica Sadun erica at ericasadun.com
Mon Dec 28 13:26:51 CST 2015


Maybe something like this?

struct KeyedLazyCache<T: Hashable, U> {
    var backingDictionary: Dictionary<T, U>
    var builderDictionary: Dictionary<T, () -> U>
    mutating func clear() {backingDictionary.removeAll()}
    mutating func valueForKey(key: T) -> U? {
        if let value = backingDictionary[key] {return value}
        if let builder = builderDictionary[key] {
            let value = builder()
            backingDictionary[key] = value
            return value
        }
        return nil
    }
}

-- E

> On Dec 28, 2015, at 11:36 AM, Rudolf Adamkovič via swift-users <swift-users at swift.org> wrote:
> 
> Hi there!
> 
> In my app, I have a very simple class that serves as a key-value cache. The whole thing is basically a lazily populated [String: AVAudioPCMBuffer] dictionary with a String -> AVAudioPCMBuffer function that generates values as needed:
> 
> final class PlayerAudioCache {
>     
>     // MARK: Retrieving audio buffers
>     
>     func audioBufferForAssetWithName(name: String) -> AVAudioPCMBuffer? {
>         addAudioBufferForAssetWithNameIfNeeded(name)
>         return cachedAudioBuffers[name]
>     }
>     
>     // MARK: Adding audio buffers
>     
>     func addAudioBufferForAssetWithNameIfNeeded(name: String) {
>         guard cachedAudioBuffers[name] == nil else { return }
>         addAudioBufferForAssetWithName(name)
>     }
>     
>     private func addAudioBufferForAssetWithName(name: String) {
>         guard let dataAsset = NSDataAsset(name: name) else { fatalError() }
>         cachedAudioBuffers[name] = dataAsset.map { URL -> AVAudioPCMBuffer in
>             AVAudioPCMBuffer(contentsOfURL: URL)!
>         }
>     }
>     
>     private var cachedAudioBuffers: [String: AVAudioPCMBuffer] = [:]
>     
> }
> 
> I feel like there is a pre-made type in Swift’s standard library for what I’m doing here. Am I right?
> 
> Ideas? Pointers?
> 
> Thank you!
> 
> R+
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20151228/61c73fac/attachment.html>


More information about the swift-users mailing list