Last active
December 17, 2023 19:47
-
-
Save chanonly123/b2eda1172b77d42f956e2513cbedb5fb to your computer and use it in GitHub Desktop.
Stored properties in Swift Extensions in Swifty way
This file contains 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
import Foundation | |
import UIKit | |
extension CustomView { | |
// can make private | |
static let storedProperties = WeakDictionary<UIView, Properties>() | |
struct Properties { | |
var url: String = "" | |
var status = false | |
var desc: String { "url: \(url), status: \(status)" } | |
} | |
var properties: Properties { | |
get { | |
return CustomView.storedProperties.get(forKey: self) ?? Properties() | |
} | |
set { | |
CustomView.storedProperties.set(forKey: self, object: newValue) | |
} | |
} | |
} | |
var view: CustomView? = CustomView() | |
print("1 print", view?.properties.desc ?? "nil") | |
view?.properties.url = "abc" | |
view?.properties.status = true | |
print("2 print", view?.properties.desc ?? "nil") | |
view = nil |
This file contains 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
import Foundation | |
import UIKit | |
private class WeakHolder<T: AnyObject>: Hashable { | |
weak var object: T? | |
let hash: Int | |
init(object: T) { | |
self.object = object | |
hash = ObjectIdentifier(object).hashValue | |
} | |
func hash(into hasher: inout Hasher) { | |
hasher.combine(hash) | |
} | |
static func ==(lhs: WeakHolder, rhs: WeakHolder) -> Bool { | |
return lhs.hash == rhs.hash | |
} | |
} | |
class WeakDictionary<T1: AnyObject, T2> { | |
private var dictionary = [WeakHolder<T1>: T2]() | |
func set(forKey: T1, object: T2?) { | |
dictionary[WeakHolder(object: forKey)] = object | |
} | |
func get(forKey: T1) -> T2? { | |
let obj = dictionary[WeakHolder(object: forKey)] | |
return obj | |
} | |
func forEach(_ handler: ((key: T1, value: T2)) -> Void) { | |
dictionary.forEach { | |
if let object = $0.key.object, let value = dictionary[$0.key] { | |
handler((object, value)) | |
} | |
} | |
} | |
func clean() { | |
var removeList = [WeakHolder<T1>]() | |
dictionary.forEach { | |
if $0.key.object == nil { | |
removeList.append($0.key) | |
} | |
} | |
removeList.forEach { | |
dictionary[$0] = nil | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment