ios - Swift中如何遍历一个类的所有属性?
ringa_lee
ringa_lee 2017-04-17 13:16:19
[iOS讨论组]

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

ringa_lee
ringa_lee

ringa_lee

全部回复(1)
PHPz

可以使用 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)
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号