Skip to content

Instantly share code, notes, and snippets.

@kingiol
Created February 11, 2019 06:25
Show Gist options
  • Save kingiol/9b237799a3c765ac44266f389ac66949 to your computer and use it in GitHub Desktop.
Save kingiol/9b237799a3c765ac44266f389ac66949 to your computer and use it in GitHub Desktop.
通过反射机制获取符合条件的属性变量
extension Mirror {
/**
* 通过反射机制获取所有符合条件的属性
*
* - parameter target: 查看哪个target中的属性
* - parameter type:
* - parameter recursivelay: 是否进行递归查询
* - parameter closure: 查看出的符合条件的属性的回调函数
*/
static func reflectProperties<T>(of target: Any,
matchingType type: T.Type = T.self,
recursively: Bool = false,
using closure: (T) -> Void) {
let mirror = Mirror(reflecting: target)
for child in mirror.children {
(child.value as? T).map(closure)
if recursively {
// To enable recursive reflection, all we have to do is to call our own method again,
// using the value of each child, and using the same closure.
Mirror.reflectProperties(of: child.value,
recursively: true,
using: closure)
}
}
}
}
// Demo
protocol Demotable {
func run()
}
struct Demo {
var name: String = "name0"
var age: Int = 0
var date: Date = Date()
var vender: String = "vender0"
var demoTable: Demotable!
func reset() {
Mirror.reflectProperties(of: self) { (child: String) in
print("fetch all type is string properties: \(child)")
}
Mirror.reflectProperties(of: self) { (demoTable: Demotable) in
print("fetch demotable properties")
demoTable.run()
}
}
}
let demo = Demo()
demo.reset()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment