获取类的属性类型和名称,而无需实例化它
如果要为某个类的实例提取属性的名称,值和类型 (Swift 3:type(of: value)
,Swift 2:value.dynamicType
),则使用 Swift 类 Mirror
。 ****
如果你的类继承自 NSObject
,你可以使用方法 class_copyPropertyList
和 property_getAttributes
来找出一个类的属性的名称和类型 - 没有它的实例。我为此在 Github 上创建了一个项目,但这里是代码:
func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? {
var count = UInt32()
guard let properties = class_copyPropertyList(clazz, &count) else { return nil }
var types: Dictionary<String, Any> = [:]
for i in 0..<Int(count) {
guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue }
let type = getTypeOf(property: property)
types[name] = type
}
free(properties)
return types
}
func getTypeOf(property: objc_property_t) -> Any {
guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)) else { return Any.self }
let attributes = attributesAsNSString as String
let slices = attributes.components(separatedBy: "\"")
guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) }
let objectClassName = slices[1]
let objectClass = NSClassFromString(objectClassName) as! NSObject.Type
return objectClass
}
func getPrimitiveDataType(withAttributes attributes: String) -> Any {
guard let letter = attributes.substring(from: 1, to: 2), let type = primitiveDataTypes[letter] else { return Any.self }
return type
}
其中 primitiveDataTypes
是一个 Dictionary,它将属性字符串中的字母映射为值类型:
let primitiveDataTypes: Dictionary<String, Any> = [
"c" : Int8.self,
"s" : Int16.self,
"i" : Int32.self,
"q" : Int.self, //also: Int64, NSInteger, only true on 64 bit platforms
"S" : UInt16.self,
"I" : UInt32.self,
"Q" : UInt.self, //also UInt64, only true on 64 bit platforms
"B" : Bool.self,
"d" : Double.self,
"f" : Float.self,
"{" : Decimal.self
]
func getNameOf(property: objc_property_t) -> String? {
guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil }
return name as String
}
它可以提取类型继承自 NSObject
的所有属性的 NSObject.Type
,如 NSDate
(Swift3:Date
),NSString
(Swift3:String
?)和 NSNumber
,但它存储在 Any
类型中(如你所见)方法返回的 Dictionary 的值)。这是由于 value types
的限制,如 Int,Int32,Bool。由于这些类型不是从 NSObject 继承的,所以在例如 Int-Int.self
上调用 .self
不会返回 NSObject.Type,而是返回类型 Any
。因此,该方法返回 Dictionary<String, Any>?
而不是 Dictionary<String, NSObject.Type>?
。
你可以像这样使用此方法:
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
}
}
guard let types = getTypesOfProperties(in: 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'
你也可以尝试将 Any
转换为 NSObject.Type
,这将成功继承 NSObject
的所有属性,然后你可以使用标准 ==
运算符检查类型:
func checkPropertiesOfBook() {
guard let types = getTypesOfProperties(in: Book.self) else { return }
for (name, type) in types {
if let objectType = type as? NSObject.Type {
if objectType == NSDate.self {
print("Property named '\(name)' has type 'NSDate'")
} else if objectType == NSString.self {
print("Property named '\(name)' has type 'NSString'")
}
}
}
}
如果你声明此自定义 ==
运算符:
func ==(rhs: Any, lhs: Any) -> Bool {
let rhsType: String = "\(rhs)"
let lhsType: String = "\(lhs)"
let same = rhsType == lhsType
return same
}
然后你甚至可以像这样检查 value types
的类型:
func checkPropertiesOfBook() {
guard let types = getTypesOfProperties(in: Book.self) else { return }
for (name, type) in types {
if type == Int.self {
print("Property named '\(name)' has type 'Int'")
} else if type == Bool.self {
print("Property named '\(name)' has type 'Bool'")
}
}
}
限制当 value types
是可选项时,此解决方案不起作用。如果你在 NSObject 子类中声明了一个属性,如下所示:var myOptionalInt: Int?
,上面的代码将找不到该属性,因为方法 class_copyPropertyList
不包含可选的值类型。