create a singleton class in swift

A singleton is a design pattern that restricts the instantiation of a class to one object. In Swift, you can create a singleton class by using a static type property to hold a single instance of the class. Here's an example implementation:

main.swift
class MySingleton {
    static let sharedInstance = MySingleton()
    
    private init() {
        // Initialization code
    }
    
    func doSomething() {
        // Method implementation goes here
    }
}
210 chars
12 lines

In this implementation, the static sharedInstance property holds a single instance of the MySingleton class. The private init method ensures that no other instances of the class can be created, and the doSomething method provides an example of a method that can be called on the singleton instance.

To use the singleton in your code, you simply call the sharedInstance property:

main.swift
let mySingleton = MySingleton.sharedInstance
mySingleton.doSomething()
71 chars
3 lines

This will give you access to the shared instance of the MySingleton class, and you can call its methods or access its properties as needed.

gistlibby LogSnag