tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.14k stars 1.03k forks source link

Getting depth of object when init to handle some nested object #1071

Open hellojunha opened 5 years ago

hellojunha commented 5 years ago

For example, we have a class like this

class User: Mappable {
    var username: String?
    var age: Int?
    var weight: Double!
    var array: [Any]?
    var dictionary: [String : Any] = [:]
    var bestFriend: User?                       // Nested User object
    var friends: [User]?                        // Array of Users
    var birthday: Date?

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        username    <- map["username"]
        age         <- map["age"]
        weight      <- map["weight"]
        array       <- map["arr"]
        dictionary  <- map["dict"]
        bestFriend  <- map["best_friend"]
        friends     <- map["friends"]
        birthday    <- (map["birthday"], DateTransform())
    }
}

and when init is called in User class, can I get the depth of nested object?

Like this

required init?(map: Map) {
    if map.depth == 1 {
        // do something
    }
}