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

nmd*_*ias 4 reflection swift2

鉴于此模型:

public class RSS2Feed {

    public var channel: RSS2FeedChannel?

    public init() {}
}

public class RSS2FeedChannel {   

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

    public init() {}

}
Run Code Online (Sandbox Code Playgroud)

我需要做什么才能获得属性名称和值 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
}
Run Code Online (Sandbox Code Playgroud)

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

文档说:

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

然而我只得到一个“Some”字符串。

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

LoV*_*oVo 5

当我理解正确时,这应该可以解决您的问题:

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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)