karstenr
karstenr

Reputation: 93

Swizzle swift property getter/setter

I have a data model class hierarchy, the base class of which is implemented in Objective-C and inherits from NSObject, where I'm redirecting property getters and setters to access an NSDictionary instead of the storage ivars. I'm doing that by dynamically replacing the getter and setter implementations at runtime.

This works fine in the Objective-C world, where my custom getters and setters get called.

It doesn't work in Swift, though. When I define an inherited model class in Swift like this:

class ScreenItem : BaseModel {
    var identifier : String?
    var group : String?
    var sort : String?
}

where BaseModel is my Obj-C base class, the Obj-C runtime can see the identifier, group and sort setter and getter methods, and I can exchange their implementations. When accessing the property from within an Obj-C context, my custom getters do get called. In a Swift context though, accessing the property just accesses the underlying ivar. (Interestingly, a @property on the BaseModel class that is thus redirected, also works in a Swift context. It's just the properties in Swift classes that don't work.)

How do I get Swift to use the Objective-C getters and setters? I could work around the issue by just using Objective-C for all my model classes, but I'd really like to define them in Swift.

Upvotes: 0

Views: 2219

Answers (1)

karstenr
karstenr

Reputation: 93

Ok, self-answering because I figured it out: it was enough to declare the variables dynamic.

class ScreenItem : BaseModel {
    dynamic var identifier : String?
    dynamic var group : String?
    dynamic var sort : String?
}

I thought inheriting from an Obj-c-class would be enough, adding the @objc directive didn't help either.

Upvotes: 4

Related Questions