mercredi 16 mars 2016

How to extract optional typed values from Mirror children in Swift?

I have a swift class like the following

public class Book {
  var title: String?
  var date: NSDate?
}

I am using reflection to run through the properties of the class:

let myBook = Book()
myBook.title = "Hello"
myBook.date = NSDate()

let mirror = Mirror(reflecting: myBook)
var propsArr = [(key: String?, value: Any)]()
let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)!
if mirrorChildrenCollection.count > 0 {
  propsArr += mirrorChildrenCollection
}

//iterate through properties
for case let (label?, value) in propsArr {
  print (label, value)

  if let val = value as? NSDate {
    var extractedDate = val
    print(extractedDate)
  }
  else if let val = value as? String {
    var extractedTitle = val
    print (extractedTitle)
  }
}

But I have a problem that the Child objects are not extracted as they are of Type Any and internally optional classes and thus do not fall into my cases. If I change title from String? to String, they do work, but I need to use optional types. What can I change in the above implementation to leave the datatype as String? and Date? and still extract the values from the Mirror?





Aucun commentaire:

Enregistrer un commentaire