From 6307c00b0c5c52596dae0f9bf2f95aab7cbe15e5 Mon Sep 17 00:00:00 2001 From: Dominic Go <18517029+dominicstop@users.noreply.github.com> Date: Fri, 7 Apr 2023 05:36:09 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=A0=20Refactor:=20Replace=20`RNIIdenti?= =?UTF-8?q?fiable`=20`counterID`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: Replace `RNIIdentifiable`'s `counterID` with `Counter.typeToCounterMap`. --- .../Helpers+Utilities/RNIIdentifiable.swift | 54 +++++++++++++++---- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/ios/src_library/Helpers+Utilities/RNIIdentifiable.swift b/ios/src_library/Helpers+Utilities/RNIIdentifiable.swift index fa788d73..e8310d13 100644 --- a/ios/src_library/Helpers+Utilities/RNIIdentifiable.swift +++ b/ios/src_library/Helpers+Utilities/RNIIdentifiable.swift @@ -7,15 +7,50 @@ import Foundation -public final class RNIObjectIdentifier { - static var counterID = -1; + +fileprivate class Counter { + static var typeToCounterMap: Dictionary = [:]; + + static func getTypeString(ofType _type: Any) -> String { + return String(describing: type(of: _type)); + }; - let id: Int = { - RNIObjectIdentifier.counterID += 1; - return RNIObjectIdentifier.counterID; - }(); + static func set(forType type: Any, counter: Int) { + let typeString = Self.getTypeString(ofType: type); + Self.typeToCounterMap[typeString] = counter; + }; + static func set(forType typeString: String, counter: Int) { + Self.typeToCounterMap[typeString] = counter; + }; + + static func get(forType type: Any) -> Int { + let typeString = Self.getTypeString(ofType: type); + + guard let counter = Self.typeToCounterMap[typeString] else { + Self.set(forType: typeString, counter: -1); + return -1; + }; + + return counter; + }; + + static func getAndIncrement(forType type: Any) -> Int { + let prevCount = Self.get(forType: type); + let nextCount = prevCount + 1; + + Self.set(forType: type, counter: nextCount); + return nextCount; + }; +}; + +public final class RNIObjectIdentifier { + let id: Int; let uuid = UUID(); + + init(type: Any) { + self.id = Counter.getAndIncrement(forType: type); + }; }; public protocol RNIIdentifiable: @@ -30,20 +65,21 @@ public protocol RNIIdentifiable: }; extension RNIIdentifiable { + public static var synthesizedIdPrefix: String { + String(describing: Self.self) + "-"; + }; public var synthesizedIdentifier: RNIObjectIdentifier { if let identifier = self.metadata { return identifier; }; - let identifier = RNIObjectIdentifier(); + let identifier = RNIObjectIdentifier(type: Self.self); self.metadata = identifier; return identifier; }; - static var synthesizedIdPrefix: String { "" }; - public var synthesizedID: Int { self.synthesizedIdentifier.id; };