SwiftReflection 0.1.2

SwiftReflection 0.1.2

alex维护。



  • Sajjon

SwiftReflection

获取从NSObject继承的类的属性的名称和类型。您不需要该类的实例。

用法

SwiftReflection依赖于Objective-C方法class_copyPropertyList来检索从NSObject继承的类的名称和类型。如果您创建了一个Book

class Book: NSObject {
    let title: String
    let author: String?
    let numberOfPages: Int
    let released: Date
    let isPocket: Bool

    init(title: String, author: String?, numberOfPages: Int, released: Date, isPocket: Bool) {
        self.title = title
        self.author = author
        self.numberOfPages = numberOfPages
        self.released = released
        self.isPocket = isPocket
    }
}

Swift Reflection可以使用getTypesOfProperties:inClass类方法检查该类的五个属性。以下检查Book类属性的代码将在下面产生注释打印

guard let types = getTypesOfProperties(inClass: Book.self) else { return }
for (name, type) in types {
  print("'\(name)' has type '\(type)'")
}
// Prints:
// 'title' has type 'NSString'
// 'numberOfPages' has type 'Int'
// 'author' has type 'NSString'
// 'released' has type 'NSDate'
// 'isPocket' has type 'Bool'

原始数据类型支持

检查哪些属性类型继承自NSObject与其他检查值类型(例如Bool, Int)属性的检查之间存在差异。如果您声明这个比较操作符,您也可以检查值类型

func ==(rhs: Any, lhs: Any) -> Bool {
    let rhsType: String = "\(rhs)"
    let lhsType: String = "\(lhs)"
    let same = rhsType == lhsType
    return same
}

现在可以使用以下方法检查书籍

func checkPropertiesOfBook() {
    guard let types = getTypesOfProperties(inClass: Book.self) else { return }

    for (name, type) in types {
        if let objectType = type as? NSObject.Type {
            if objectType == NSDate.self {
                print("found NSDate")
            }
        } else {
            if type == Int.self {
                print("found int")
            }
        }
    }
}

限制

我还没有能够为以下情况的项目提供支持:当值类型(非类类型)是可选的。如果你在你NSObject子类中声明了如下属性:var myOptionalInt: Int?,我的解决方案将不起作用,因为方法class_copyPropertyList找不到这些属性。

有人有这个问题的解决方案吗?