Created
March 1, 2024 05:37
-
-
Save Lavmint/68df933aaad11131b4b7d549d4c7a07d to your computer and use it in GitHub Desktop.
Merge NSObjects
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
protocol ObjectMerger { | |
func merge<T>(_ source: T, into dest: T, overwrites: Bool) | |
} | |
struct StandartObjectMerger: ObjectMerger { | |
func merge<T>(_ source: T, into dest: T, overwrites: Bool) { | |
guard let src = source as? NSObject else { | |
return | |
} | |
let classType: AnyClass! = NSClassFromString(src.className) | |
var numOfProperties: UInt32 = 0 | |
let properties = class_copyPropertyList(classType, &numOfProperties) | |
for i in 0..<numOfProperties { | |
let idx = Int(i) | |
let prop = properties![idx] | |
let rawAttrs = String(cString: property_getAttributes(prop)!) | |
let attrs = Set(rawAttrs.components(separatedBy: ",")) | |
if attrs.contains("R") { | |
continue | |
} | |
let nsKey = NSString(utf8String: property_getName(prop))! | |
let key = nsKey as String | |
let newValue = src.value(forKey: key) | |
let dst = dest as! NSObject | |
if overwrites { | |
dst.setValue(newValue, forKey: key) | |
} else if newValue != nil { | |
dst.setValue(newValue, forKey: key) | |
} else { | |
//skip nil if not overwrites | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment