迅速反思2

编程入门 行业动态 更新时间:2024-10-16 16:41:36
本文介绍了迅速反思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.

我研究了以下资源:

  • netguru.co/blog/reflection-swift
  • nshipster/mirrortype/
  • netguru.co/blog/reflection-swift
  • nshipster/mirrortype/
  • 更新 我在这里找到了答案: stackoverflow/a/32846514/4959077 .但这并不能告诉我们如何找出反映价值的类型.如果值是int,并且我们将其解析为String,那么它将给出错误.

    UPDATE I have found the an answer here: stackoverflow/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

    本文发布于:2023-11-26 20:39:38,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1635116.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!