Skip to content

Instantly share code, notes, and snippets.

@jesusdomin
Last active August 29, 2015 14:07
Show Gist options
  • Save jesusdomin/f82c33fec215d04fe99e to your computer and use it in GitHub Desktop.
Save jesusdomin/f82c33fec215d04fe99e to your computer and use it in GitHub Desktop.
Singleton in Swift example
// More info: http://code.martinrue.com/posts/the-singleton-pattern-in-swift
import UIKit
class ItemStore {
class var sharedInstance: ItemStore {
struct Static {
static var instance: ItemStore?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = ItemStore()
}
return Static.instance!
}
private var items = [Item]()
func createItem() -> Item {
var newItem = Item.randomItem()
items.append(newItem)
return newItem
}
func allItems() -> [Item] {
return [Item](items)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment