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

Reflection 如何使用Swift 2.0和反射获取属性名称及其值?,reflection,swift2,Reflection,Swift2,鉴于这种模式: 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
}
最后,我尝试使用反射创建一个与实例匹配的
字典
,但到目前为止,我无法获取实例的属性名称和值

文件说:

可选标签可在适当时使用,例如,用于表示存储属性或活动枚举案例的名称,并将在字符串传递给后代方法时用于查找

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


此外,value属性返回一个类型为
RSS2FeedChannel
的字符串,而我希望每个子级都是“反射实例结构的元素”

您可以在镜像对象上使用
子代
方法来获取此信息。如果找不到值或选项不包含值,它将返回nil

let mirror = Mirror(reflecting: feed.channel)
let child1 = mirror.descendant("Some", "title") // "The Channel Title"

// or on one line
let child3 = Mirror(reflecting: feed).descendant("channel", "Some", "title")

当我理解正确时,这将解决您的问题:

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
}

我发现当可选项不包含任何值时,child1的值不仅仅是
nil
。看见