Skip to content

Instantly share code, notes, and snippets.

@st-small
Last active July 14, 2018 17:15
Show Gist options
  • Save st-small/310e256237e8e157f407aeb90c0ab252 to your computer and use it in GitHub Desktop.
Save st-small/310e256237e8e157f407aeb90c0ab252 to your computer and use it in GitHub Desktop.
small example to make the reflection in Swift 4.0
import UIKit
public class Human: NSObject {
@objc dynamic public var firstName = "*****"
@objc dynamic public var lastName = "*****"
@objc dynamic public var age = 0
@objc dynamic public var hobby = "*****"
@objc dynamic public var university = "*****"
@objc dynamic public var sportLeague = "*****"
override init() {}
public func setValue(byValue: String, withDict: Dictionary<String, Any>) {
if let value = withDict[byValue] {
self.setValue(value, forKey: byValue)
}
}
}
let dict: [String : Any] = ["firstName" : "Ivan",
"lastName" : "Ivanov",
"age" : 35,
"hobby" : "swimming",
"university" : "",
"sportLeague" : ""]
let human = Human()
let props = Mirror(reflecting: Human()).children.compactMap { $0.label }
for prop in props {
human.setValue(byValue: prop, withDict: dict)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment