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

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)……
求正确的改写方式或者遍历方法……


可以使用 reflect() 来遍历一个实例里面所有的属性,除了 computed property 以外的所有属性都可遍历。没找到方法直接对 class 进行遍历,所以必须至少创建一个实例才能工作。

示例代码:https://gist.github.com/huandu/d976f7994d2fd159398b

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:
//
//     key: simpleProp
//     key: structProp
for var index = 0; index < count; ++index {
    let key = mirror[index].0

    // "super" refers to super class if any.
    if key == "super" && index == 0 {
        continue
    }

    print("key: ")
    println(key)
}
【热门文章】
【热门文章】