jeudi 23 juillet 2015

Using reflection to set object properties without using setValue forKey

In Swift it's not possible use .setValue(..., forKey: ...)

  • nullable type fields like Int?
  • properties that have an enum as it's type
  • an Array of nullable objects like [MyObject?]

There is one workaround for this and that is by overriding the setValue forUndefinedKey method in the object itself.

Since I'm writing a general object mapper based on reflection. See EVReflection I would like to minimize this kind of manual mapping as much as possible.

Is there an other way to set those properties automatically?

Here is the workaround that I'm currently using and try to eliminate:

class TestObject3: EVObject {
    var objectValue: String = ""
    var nullableType: Int?

    // This construction can be used to bypass the issue for setting a nullable type field
    override func setValue(value: AnyObject!, forUndefinedKey key: String) {
        switch key {
            case "nullableType":
                nullableType = value as? Int
        default:
            NSLog("---> setValue for key '\(key)' should be handled.")
        }
    }
}

// Which can be tested with:
var test = TestObject3()
test.setValue(0, forKey: "nullableType")





Aucun commentaire:

Enregistrer un commentaire