开发者社区> 问答> 正文

Swift中如何遍历一个类的所有属性?

CocoaChina中找到了一段OC中遍历所有属性的代码

int i;
int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([aPerson class], &propertyCount);

for ( i=0; i < propertyCount; i++ ) {

objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSLog(@"Person has a property: '%s'", propertyName);

}
但是试了试似乎没法直接改写成Swift,propertyList那里得到的是UnsafeMutablePointer(nil)……
求正确的改写方式或者遍历方法……

展开
收起
a123456678 2016-07-27 15:25:39 3197 0
1 条回答
写回答
取消 提交回答
  • import Foundation
    
    struct Point {
        var x = 0.0
        var y = 0.0
    }
    
    class PropertyHub {
        var simpleProp = "Foo"
        var structProp = Point()
    
        // computed property is not visible in reflect().
        var computedProp : Point {
            get {
                return Point(x: structProp.x + 100.0, y: structProp.y - 100.0)
            }
        }
    }
    
    // we have to create an instance before calling reflect().
    var hub = PropertyHub()
    
    let mirror = reflect(hub)
    let count = mirror.count
    
    // this for loop will print:
    //
    2019-07-17 20:00:41
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关课程

更多

相关电子书

更多
OpenStack Swift 海量小文件优化之路 立即下载
From Java/Android to Swift iOS 立即下载
Swift在Airbnb的应用实践 立即下载