jazzedge
12/1/2017 - 7:31 PM

Swift - Singletons

Singletons
A singleton is a single instance of a class that is present at all times in memory. So why do we care about this? Well, let's say that you are building an app that connects to a database. You need a place to put all of your data service connections. This would be a perfect place to use singletons. Look at the code below; it will show you how to construct a singleton:

// Declaration
class DataService {
    static var shared = DataService()
     
    func createUser() {
    }
}
 
// Call-site
DataService.shared.createUser()


If you follow these simple tips, your app will be easier to maintain, and bugs will be more obvious to find before your customers do.