evermeer / EVReflection

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift
Other
965 stars 119 forks source link

How to output getters via .toJsonString method #292

Closed bj97301 closed 6 years ago

bj97301 commented 6 years ago

I have something like this:

    var _firstName: String?
    var firstName: String? {
        get {
            guard AppConfigs.shouldFakeApi else {
                return _firstName
            }
            return AppConfigs.demoUser["firstName"] ?? _firstName
        }
        set(value) {
            _firstName = value
        }
    }

I would like the firstName to be included in the .toJsonString response. Any idea how I should go about doing this?

evermeer commented 6 years ago

In your code above the _firstName is a property that can be read using reflection. firstName is a calculated property which is actually 2 functions (getter and setter function) These cannot be read using reflection.

A workaround could be something like the code below. You do have to be aware that the actual value is set to the config value if shoulFakeApi is set. Also it outputs _firstName instead firstName but that could be changed using property mapping

public class myObject: EVObject {
    var _firstName: String?

 var firstName: String? {
        get {
                return _firstName        
        }
        set(value) {
            if AppConfigs.shouldFakeApi else {
                _firstName = AppConfigs.demoUser["firstName"] ?? value
            } else {
                _firstName = value
           }
        }
    }

    required public init() {
        if shouldFakeApi { firstName = "ConfigFirstName"}
    }
}
evermeer commented 6 years ago

Just let me know if you still have questions.