Swift 之用 Swift 运行时获取对象属性列表
2017-12-02 本文已影响0人
willokyes
//
// Animal.swift
// demo
//
// Created by 八月夏木 on 2017/11/30.
// Copyright © 2017年 八月夏木. All rights reserved.
//
import UIKit
class Animal: NSObject {
@objc var name: String?
@objc var age: Int = 0
@objc var species: String?
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
class func propertyList() -> [String] {
var count: UInt32 = 0
let list = class_copyPropertyList(self, &count)
print("属性个数:\(count)")
//
for i in 0..<Int(count) {
let ppy = list?[i]
let cName = property_getName(ppy!)
let name = String(utf8String:cName)
print(name!)
}
// guard let
for i in 0..<Int(count) {
guard let ppy = list?[i],
let name = String(utf8String:property_getName(ppy)) else {
continue
}
print(name)
}
// guard let
for i in 0..<Int(count) {
guard let ppy = list?[i],
let cName = property_getName(ppy) as Optional,
let name = String(utf8String:cName) else {
continue
}
print(name)
}
free(list)
return []
}
}