Search code examples
reflectionswift2mirrorxcode7.3

Swift 2 Reflection Error


I have look around a swift code to try and make a reflection function that serialized an object into JSON. The trouble is when i call the initializer to get the reflection it throws a crazy error

struct Address {
    var street: String
}

struct Person {
    var name: String = "Dre"
    var age: Int = 33
    var dutch: Bool = false
    var address: Address? = Address(street: "Clark Drive")
}

// Throws an error on the next line
let mirror = Mirror(reflecting: Person) 

When i try to set the value of mirror to the result of Mirror initialization i get the following errors:

  1. Missing argument label 'reflecting:' in call
  2. Cannot create a single-element tuple with an element label

Any idea what could be going wrong here?


Solution

  • You need to pass an instance of Person instead of the class Person. E.g:

    struct Address {
        var street: String
    }
    
    struct Person {
        var name: String = "Dre"
        var age: Int = 33
        var dutch: Bool = false
        var address: Address? = Address(street: "Clark Drive")
    }
    
    let person = Person()
    let mirror = Mirror(reflecting: person)
    
    print(mirror.displayStyle)
    for case let (label?, value) in mirror.children {
        print(label, value)
    }
    

    Prints:

    Optional(Struct)
    name Dre
    age 33
    dutch false
    address Optional(Address(street: "Clark Drive"))
    Mirror for Bookmark