dimanche 2 août 2015

How to get a property name and its value using Swift 2.0, and reflection?

Given this Model:

public class RSS2Feed {

    public var channel: RSS2FeedChannel?

    public init() {}

}

public class RSS2FeedChannel {   

    public var title: String?

    public var description: String?

    public init() {}

}

What would I need to do in order to get the property names and values of an RSS2FeedChannel instance?

Here's what I'm trying:

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
}

Ultimately, I'm trying to create a Dictionary that matches the instance, using reflection, but so far I'm unable to get the properties name and values of the instance.

Documentation says that: "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.", yet I only get a "Some" string.

Also, the value property is returning a string with the Type (RSS2FeedChannel) when I would expect each children to be "An element of the reflected instance's structure."!

Thank you!





Aucun commentaire:

Enregistrer un commentaire