Using Mirror
这是一个纯粹的快速解决方案,但有一些局限性:
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对象的空数组
不会返回计算(computed)属性,即:
var favoriteFood: String { return "Lemon Cake" }
如果self
是一个类的实例(比如,一个 struct ),它不会报告其超类的属性,即:
class Person : PropertyNames {
var name = "Bruce Wayne"
}
class Superhero : Person {
var hasSuperpowers = true
}
Superhero().propertyNames() // ["hasSuperpowers"] — no "name"
根据你想要的行为,你可以使用superclassMirror()
来解决这个问题.
Using class_copyPropertyList
如果您使用的是Objective-C对象,您可以使用以下方法:
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)
如果classToInspect
为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
(或者重复使用与扩展相同的逻辑),就可以了.