加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用Swift 2.0和反射获取属性名称及其值?

发布时间:2020-12-14 04:36:56 所属栏目:百科 来源:网络整理
导读:鉴于此模型: public class RSS2Feed { public var channel: RSS2FeedChannel? public init() {}}public class RSS2FeedChannel { public var title: String? public var description: String? public init() {}} 为了获取RSS2FeedChannel实例的属性名称和值
鉴于此模型:

public class RSS2Feed {

    public var channel: RSS2FeedChannel?

    public init() {}
}

public class RSS2FeedChannel {   

    public var title: String?
    public var description: String?

    public init() {}

}

为了获取RSS2FeedChannel实例的属性名称和值,我需要做什么?

这是我正在尝试的:

let feed = RSS2Feed()
feed.channel = RSS2FeedChannel()
feed.channel?.title = "The Channel Title"

let mirror = Mirror(reflecting: feed.channel)
mirror.children.first // ({Some "Some"},{{Some "The Channel Title...

for (index,value) in mirror.children.enumerate() {
    index // 0
    value.label // "Some"
    value.value // RSS2FeedChannel
}

最后,我正在尝试创建一个匹配实例的Dictionary,使用反射,但到目前为止,我无法获取实例的属性名称和值.

文档说:

The optional label may be used when appropriate,e.g. to represent the name of a stored property or of an active enum case,and will be used for lookup when Strings are passed to the descendant method.

然而,我只得到一个“一些”字符串.

此外,当我希望每个子节点都是“反射实例结构的元素”时,value属性返回一个带有类型RSS2FeedChannel的字符串.

解决方法

当我理解正确这应该解决你的问题:

func aMethod() -> Void {
    let feed = RSS2Feed()
    feed.channel = RSS2FeedChannel()
    feed.channel?.title = "The Channel Title"
//  feed.channel?.description = "the description of your channel"

    guard  let channel = feed.channel else {
        return
    }

    let mirror = Mirror(reflecting: channel)
    for child in mirror.children {
        guard let key = child.label else {
            continue
        }
        let value = child.value

        guard let result = self.unwrap(value) else {
            continue
        }

        print("(key): (result)")
    }
}

private func unwrap(subject: Any) -> Any? {
    var value: Any?
    let mirrored = Mirror(reflecting:subject)
    if mirrored.displayStyle != .Optional {
        value = subject
    } else if let firstChild = mirrored.children.first {
        value = firstChild.value
    }
    return value
}

只是swift 3的一些小变化:

private func unwrap(_ subject: Any) -> Any? {
    var value: Any?
    let mirrored = Mirror(reflecting:subject)
    if mirrored.displayStyle != .optional {
        value = subject
    } else if let firstChild = mirrored.children.first {
        value = firstChild.value
    }
    return value
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读