Last active
August 29, 2015 14:07
-
-
Save jesusdomin/f82c33fec215d04fe99e to your computer and use it in GitHub Desktop.
Singleton in Swift example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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