swift中类的属性列表 [英] List of class's properties in swift

查看:34
本文介绍了swift中类的属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:在此处为目标 c 发布了一个类似的问题,但我想快速实现.

Note: there is a similar question posted for objective c over here, but I want to achieve it in swift.

我有一个像这样在 swift 中声明的类:

I have a class declared in swift like this:

import UIKit

class EachDayCell : UITableViewCell
{

    @IBOutlet var dateDisplayLabel : UITextField
    @IBOutlet var nameDisplayLabel : UITextField

    @IBAction func goToPendingItems(sender : AnyObject) {
    }
    @IBAction func showDateSelectionPicker(sender : AnyObject) {
    }

    init(style: UITableViewCellStyle, reuseIdentifier: String!)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    }
}

现在我想在 swift enlisting 中获取一个数组:dateDisplayLabel、nameDisplayLabel.

Now I want to get an array in swift enlisting: dateDisplayLabel, nameDisplayLabel.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

Using Mirror

这是一个有一些限制的纯 Swift 解决方案:

Using Mirror

Here's a pure Swift solution with some limitations:

protocol PropertyNames {
    func propertyNames() -> [String]
}

extension PropertyNames
{
    func propertyNames() -> [String] {
        return Mirror(reflecting: self).children.flatMap { $0.label }
    }
}

class Person : PropertyNames {
    var name = "Sansa Stark"
    var awesome = true
}

Person().propertyNames() // ["name", "awesome"]

限制:

  • 为 Objective-C 对象返回一个空数组
  • 不会返回计算属性,即:

  • Returns an empty array for Objective-C objects
  • Will not return computed properties, i.e.:

var favoriteFood: String { return "Lemon Cake" }

  • 如果 self 是一个类的实例(相对于一个结构体),它不会报告它的超类的属性,即:

  • If self is an instance of a class (vs., say, a struct), this doesn't report its superclass's properties, i.e.:

    class Person : PropertyNames {
        var name = "Bruce Wayne"
    }
    
    class Superhero : Person {
        var hasSuperpowers = true
    }
    
    Superhero().propertyNames() // ["hasSuperpowers"] — no "name"
    

    您可以使用 superclassMirror() 解决此问题,具体取决于您想要的行为.

    You could work around this using superclassMirror() depending on your desired behavior.

    如果您使用的是 Objective-C 对象,您可以使用这种方法:

    If you're using Objective-C objects you can use this approach:

    var count = UInt32()
    let classToInspect = NSURL.self
    let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count)
    var propertyNames = [String]()
    let intCount = Int(count)
    for var i = 0; i < intCount; i++ {
        let property : objc_property_t = properties[i]
        guard let propertyName = NSString(UTF8String: property_getName(property)) as? String else {
            debugPrint("Couldn't unwrap property name for (property)")
            break
        }
    
        propertyNames.append(propertyName)
    }
    
    free(properties)
    print(propertyNames)
    

    如果classToInspectNSURL,则输出到控制台:

    The output to the console if classToInspect is NSURL:

    ["pathComponents", "lastPathComponent", "pathExtension", "URLByDeletingLastPathComponent", "URLByDeletingPathExtension", "URLByStandardizingPath", "URLByResolvingSymlinksInPath", "dataRepresentation", "absoluteString", "relativeString", "baseURL", "absoluteURL", "scheme", "resourceSpecifier", "host", "port", "user", "password", "path", "fragment", "parameterString", "query", "relativePath", "hasDirectoryPath", "fileSystemRepresentation", "fileURL", "standardizedURL", "filePathURL"]

    这在操场上是行不通的.只需将 NSURL 替换为 EachDayCell(或重用与扩展相同的逻辑),它应该可以工作.

    This won't work in a playground. Just replace NSURL with EachDayCell (or reuse the same logic as an extension) and it should work.

    这篇关于swift中类的属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆