Last active
August 11, 2021 06:32
-
-
Save GGJJack/f25d7795c50a2f24c18defd8840df67f to your computer and use it in GitHub Desktop.
Swift reflection test example
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
| // Target Class | |
| class Sample: NSObject { | |
| @objc var id: Int = 0 | |
| @objc var name: String? = nil | |
| var test: String? = nil | |
| } | |
| // Swift Style | |
| let element = Sample() | |
| let mirror = Mirror(reflecting: element) | |
| for child in mirror.children { | |
| print("Key : \(child.label) / Value : \(child.value)") | |
| } | |
| // Log | |
| // Key : Optional("id") / Value : 0 | |
| // Key : Optional("name") / Value : nil | |
| // Key : Optional("test") / Value : nil | |
| // Objective-C Style | |
| // Hint from //https://stackoverflow.com/questions/20973806/property-getattributes-does-not-make-difference-between-retain-strong-weak-a | |
| var propertiesCount : CUnsignedInt = 0 | |
| let propertiesInAClass = class_copyPropertyList(Sample.self, &propertiesCount) | |
| for i in 0..<Int(propertiesCount) { | |
| guard let property = propertiesInAClass?[i] else { continue } | |
| let attrs = property_getAttributes(property) | |
| let strKey = NSString(utf8String: property_getName(property)) as String? | |
| print("Key : \(strKey), Type : \(String(cString: attrs!))") | |
| } | |
| // Log | |
| // Key : Optional("id"), Type : Tq,N,Vid | |
| // Key : Optional("name"), Type : T@"NSString",N,C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment