迅速反思2 [英] Reflection in swift 2
问题描述
我有一个班级用户:
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()方法来获取所有数据成员及其名称和值的数组.
In swift 1.2, I was using reflect() method to get array of all the data members with their names and values.
现在,我将其更新为swift 2后,出现以下错误:
Now, after I have updated to swift 2, I am getting the following error:
'reflect'不可用:调用'Mirror(reflecting :)'初始化程序
'reflect' is unavailable: call the 'Mirror(reflecting:)' initializer
通过一些试验,我能够通过以下方式获取数据成员的数量:Int(Mirror(reflecting: self).children.count)
,但仍然无法获取成员名称及其值.
With some trials, I was able to get the count of data members by this: Int(Mirror(reflecting: self).children.count)
, but still, I am unable to get the member name and its value.
我研究了以下资源:
- https://netguru.co/blog/reflection-swift
- http://nshipster.com/mirrortype/
更新 我在这里找到了答案: https://stackoverflow.com/a/32846514/4959077 .但这并不能告诉我们如何找出反映价值的类型.如果值是int,并且我们将其解析为String,那么它将给出错误.
UPDATE I have found the an answer here: https://stackoverflow.com/a/32846514/4959077. But this doesn't tell how to find out the type of reflected value. If the value is int and we parse it into String then it gives error.
推荐答案
您可以按如下方式访问反映的属性标签"的名称,值和类型:
You may access the reflected attribute "label" name, value and type as follows:
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)")
}
}
注意:在每个问题的后续调查中,显示了三种确定反射值类型的方法.
Note: per the question followup, three approaches to determine the type of the reflected value are shown.
这篇关于迅速反思2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!