How to get the name of a property 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 do I need to do to get the property names and values ​​of the RSS2FeedChannel instance?

Here is what I am 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 can’t get the name of the property and the value of the instance.

The documentation states that:

If necessary, an optional label may be used, for example. to represent the name of the stored property or the active enumeration case and will be used to search when strings are passed to the child method.

But I only get the string "Some".

In addition, the value property returns a string of type RSS2FeedChannel when I expect each child to be a "Reflected Instance Structure Element."

+4
source share
2 answers

When I understand correctly, this should solve ur problem:

 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 } 

just small changes for quick 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 } 
+4
source

You can use the descendent method on the Mirror object to get this information. It will return nil if no values ​​are found or optional do not contain a value.

 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") 
+1
source

All Articles