Skip to content

Commit

Permalink
⭐️ Impl: RNIWeakRef
Browse files Browse the repository at this point in the history
Related to: TODO:2023-03-04-15-39-46 - Impl: RNIModalManager
  • Loading branch information
dominicstop committed Mar 11, 2023
1 parent 85c153d commit 647e876
Showing 1 changed file with 66 additions and 0 deletions.
66 changes: 66 additions & 0 deletions ios/src_library/React Native/RNIWeak/RNIWeakRef.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
//
// RNIWeakRef.swift
// react-native-ios-modal
//
// Created by Dominic Go on 3/11/23.
//

import Foundation


public class RNIWeakRef<T> {
public weak var rawRef: AnyObject?;

public var synthesizedRef: T? {
self.rawRef as? T;
};

init(with ref: AnyObject) {
self.rawRef = ref;
};
};

public class RNIWeakDictionary<K: Hashable, T> {

fileprivate var _dict: [K: RNIWeakRef<T>] = [:];

var purgedDict: [K: RNIWeakRef<T>] {
get {
self._dict.compactMapValues {
$0.rawRef != nil ? $0 : nil;
}
}
};

var dict: [K: RNIWeakRef<T>] {
get {
let purgedDict = self.purgedDict;
self._dict = purgedDict;

return purgedDict;
}
}

func set(for key: K, with value: T){
self._dict[key] = RNIWeakRef(with: value as AnyObject);
};

func get(for key: K) -> T? {
guard let ref = self._dict[key]?.synthesizedRef else {
self._dict.removeValue(forKey: key);
return nil;
};

return ref;
};

subscript(key: K) -> T? {
get {
self.get(for: key);
}
set {
guard let ref = newValue else { return };
self.set(for: key, with: ref);
}
}
};

0 comments on commit 647e876

Please sign in to comment.