Created
July 4, 2025 10:29
-
-
Save brownsoo/14de28c1f2a9a4bcedac3b4bbdfe884c to your computer and use it in GitHub Desktop.
Swift 용 메모리 캐시 (NSCache Wrapper)
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
// | |
// SimpleMemCache.swift | |
// HiCrawlingTimetable | |
// | |
// Created by 브라운수 on 7/4/25. | |
// from: https://www.swiftbysundell.com/articles/caching-in-swift/ | |
import Foundation | |
final class SimpleMemCache<Key: Hashable, Value> { | |
final class WrappedKey: NSObject { | |
let key: Key | |
init(_ key: Key) { self.key = key } | |
override var hash: Int { return key.hashValue } | |
override func isEqual(_ object: Any?) -> Bool { | |
guard let value = object as? WrappedKey else { | |
return false | |
} | |
return value.key == key | |
} | |
} | |
final class Entry { | |
let value: Value | |
init(value: Value) { | |
self.value = value | |
} | |
} | |
private let wrapped = NSCache<WrappedKey, Entry>() | |
func insert(_ value: Value, forKey key: Key) { | |
let entry = Entry(value: value) | |
wrapped.setObject(entry, forKey: WrappedKey(key)) | |
} | |
func value(forKey key: Key) -> Value? { | |
let entry = wrapped.object(forKey: WrappedKey(key)) | |
return entry?.value | |
} | |
func removeValue(forKey key: Key) { | |
wrapped.removeObject(forKey: WrappedKey(key)) | |
} | |
} | |
extension SimpleMemCache { | |
subscript(key: Key) -> Value? { | |
get { return value(forKey: key) } | |
set { | |
guard let value = newValue else { | |
// If nil was assigned using our subscript, | |
// then we remove any value for that key: | |
removeValue(forKey: key) | |
return | |
} | |
insert(value, forKey: key) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment