[swift-users] Lazily populated dictionary

Rudolf Adamkovič salutis at me.com
Mon Dec 28 12:36:10 CST 2015

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? {
        return cachedAudioBuffers[name]
    // MARK: Adding audio buffers
    func addAudioBufferForAssetWithNameIfNeeded(name: String) {
        guard cachedAudioBuffers[name] == nil else { return }
    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!

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

More information about the swift-users mailing list