title: Singleton in Swift
body: <p>I've been trying to implement a singleton to be used as a cache for photos which I uploaded to my iOS app from the web. I've attached three variants in the code below.  I tried to get variant 2 working but it is causing a compiler error which I do not understand and would like to get help on what am I doing wrong.  Variant 1 does the caching but I do not like the use of a global variable.  Variant 3 does not do the actual caching and I believe it is because I am getting a copy in the assignment to var ic = ...., is that correct?</p>
  
  <p>Any feedback and insight will be greatly appreciated.</p>
  
  <p>Thanks,
  Zvi</p>
  
  <pre><code>import UIKit
  
  private var imageCache: [String: UIImage?] = [String : UIImage?]()
  
  class ImageCache {
      class var imageCache: [String : UIImage?] {
          struct Static {
              static var instance: [String : UIImage?]?
              static var token: dispatch_once_t = 0
          }
  
          dispatch_once(&amp;Static.token) {
              Static.instance = [String : UIImage?]()
          }
          return Static.instance!
      }
  }
  
  class ViewController: UIViewController {
  
      @IBOutlet weak var imageView: UIImageView!
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          imageView.image = UIImage(data: NSData(contentsOfURL: NSURL(string: "http://images.apple.com/v/iphone-5s/gallery/a/images/download/photo_1.jpg")!)!)
  
          //variant 1 - this code is working
          imageCache["photo_1"] = imageView.image
          NSLog(imageCache["photo_1"] == nil ? "no good" : "cached")
  
          //variant 2 - causing a compiler error on next line: '@lvalue $T7' is not identical to '(String, UIImage?)'
          //ImageCache.imageCache["photo_1"] = imageView.image
          //NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
  
          //variant 3 - not doing the caching
          //var ic = ImageCache.imageCache
          //ic["photo_1)"] = imageView.image
          //NSLog(ImageCache.imageCache["photo_1"] == nil ? "no good" : "cached")
      }
  }
  </code></pre>