Sobes.tech
Junior — Middle

How can you independently implement a caching mechanism without involving third-party libraries?

sobes.tech AI

Answer from AI

To independently implement a simple caching mechanism in iOS without third-party libraries, you can use a dictionary to store data with keys and values, and also add logic to manage cache lifetime.

Example in Swift:

class SimpleCache<Key: Hashable, Value> {
    private var cache = [Key: (value: Value, expiry: Date?)]()
    private let defaultExpiry: TimeInterval

    init(defaultExpiry: TimeInterval = 300) { // 5 minutes by default
        self.defaultExpiry = defaultExpiry
    }

    func set(_ value: Value, for key: Key, expiry: TimeInterval? = nil) {
        let expiryDate = expiry != nil ? Date().addingTimeInterval(expiry!) : Date().addingTimeInterval(defaultExpiry)
        cache[key] = (value, expiryDate)
    }

    func get(_ key: Key) -> Value? {
        guard let entry = cache[key] else { return nil }
        if let expiry = entry.expiry, expiry < Date() {
            cache.removeValue(forKey: key)
            return nil
        }
        return entry.value
    }

    func remove(_ key: Key) {
        cache.removeValue(forKey: key)
    }

    func clear() {
        cache.removeAll()
    }
}

This class allows storing objects with keys, automatically removing expired data, and managing the cache manually.

How can you independently implement a caching… - sobes.tech