Luong Dinh Luong Dinh - 10 days ago 4
Swift Question

Swift Reflection mapping attributes

Are there anything look like java reflection in swift or I have to always map one by one attribute like following code?

class User: Model {

var name: String

override init(data: Dictionary<String, AnyObject>){
super.init(data: data)
self.name = data["name"] as? String
if let vouchers_count = data["vouchers_count"] as? Int {
self.vouchers_count = vouchers_count
}
}

Answer

You could use libraries such as EVReflection.

import EVReflection

class User: EVObject {
    var name: String = ""
    var vouchers_count: Int = 0
}

let alice = User(json: "{\"name\":\"alice\",\"vouchers_count\":1}")
debugPrint(alice)
/*
    testUser = {
    "name" : "alice",
    "vouchers_count" : 1
    }
*/

let bob = User(json: "{\"name\":\"bob\"}")
debugPrint(bob)
/*
    testUser = {
    "name" : "bob",
    "vouchers_count" : 0
    }
*/
Comments