Home > AI > Language > Swift >

Singleton

Example: Some common system singletons

// Shared URL Session
let sharedURLSession = URLSession.shared

// Default File Manager
let defaultFileManager = FileManager.default

// Standard User Defaults
let standardUserDefaults = UserDefaults.standard

// Default Payment Queue
let defaultPaymentQueue = SKPaymentQueue.default()

Example 2: custome singletons.

import Foundation
import SwiftUI



protocol ImageCache {
    subscript(_ urlString: String) -> UIImage? {get set }
}


struct MyImageCache: ImageCache {
    subscript(urlString: String) -> UIImage? {
        get {
            cache.object(forKey: urlString as NSString)
        }
        set {
            newValue == nil ? cache.removeObject(forKey: urlString as NSString) : cache.setObject(newValue!, forKey: urlString as NSString)
        }
    }
    
    var cache = NSCache<NSString, UIImage>()
}




// Singleton
extension MyImageCache {
    static private let shared: MyImageCache = MyImageCache()
    
    static func getShared() -> MyImageCache {
        return shared
    }
}

Leave a Reply