我有一个类User:
import UIKit
import ObjectMapper
class User: NSObject, CustomStringConvertible, Mappable {
var FirstName: NSString! ;
var LastName: NSString! ;
required init?(_ map: Map){
}
func mapping(map: Map) {
FirstName <- map["FirstName"]
LastName <- map["LastName"]
}
override var description:String {
var s:String=""
//USE REFLECTION TO GET NAME AND VALUE OF DATA MEMBERS
for var index=1; index<reflect(self).count; ++index {
s += (reflect(self)[index].0 + ": "+reflect(self)[index].1.summary+"t")
}
return s
}
}
在swift 1.2中,我使用reflect()方法来获取所有数据成员及其名称和值的数组。
现在,在我更新到swift 2之后,我得到以下错误:
'reflect'不可用:调用'Mirror(reflecting:)'初始化器
通过一些尝试,我能够通过以下方式获得数据成员的计数:Int(Mirror(reflecting: self).children.count)
,但是,我仍然无法获得成员名称及其值。
我查阅了以下资源:
- https://netguru.co/blog/reflection-swift
- http://nshipster.com/mirrortype/
我在这里找到了答案:https://stackoverflow.com/a/32846514/4959077。但这并没有告诉我们如何找出反射值的类型。如果值是int而我们将其解析为String则会给出错误
您可以按照以下方式访问反射属性"label"的名称、值和类型:
let mirror = Mirror(reflecting: SomeObject)
var dictionary = [String: Any]()
for child in mirror.children {
guard let key = child.label else { continue }
let value: Any = child.value
dictionary[key] = value
switch value {
case is Int: print("integer = (anyValue)")
case is String: print("string = (anyValue)")
default: print("other type = (anyValue)")
}
switch value {
case let i as Int: print("• integer = (i)")
case let s as String: print("• string = (s)")
default: print("• other type = (anyValue)")
}
if let i = value as? Int {
print("•• integer = (i)")
}
}
注:根据后续问题,给出了三种确定反映值类型的方法
我有一个解决方案,可以找到给定从NSObject
继承的任何类的属性的名称和类型。
我在这里写了一篇关于StackOverflow的长篇解释,我的项目可以在Github上找到,
简而言之,你可以这样做(但真的检查代码Github):
public class func getTypesOfProperties(inClass 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
}