swift class property override question.

I have a class hierarchy.  and ideally I would like to manage the class hierarchy without regard to which subclass I am dealing with.

But I have run afoul what appears to me to be a design limitation of Swift. I’m hoping wiser individuals will know how to get around this limitation.


my subclasses (NSObject subclasses, this is a Mac os Cocoa app) exist exclusively to manage a single property. each class, handles a different type. But the patterns and behavior are all the same…

for instance, subClass 01 manages a property:

var val : String

while subClass02 manages :

var val : Double


I have tried defining this property in the base class as :

var val : Any

and then overriding it in subclasses:

override var val : Double (etc…)


this of course always throws an error. But it also forces me into the awkward position of checking the class type every single time I have to interact with the “val” property:


if let numObj = item as? subClass01{
//do stuff

}else if let strObj = item as? subClass02{
// do literally the same exact stuff.. because it doesn’t matter WHAT the type of the property is for what I’m trying to do.



I have many of these classes, and my code is getting very thick with all of this boilerplate crap. it’s hard to follow at times, and it forces a number of conventions that lead to otehr limitations (such as… if I would like to add a new subclass to my hierarchy, I now have to find every instance where I’ve had to explicitly check for type, and add some code.)


is there _ANY_ way to add a property to a parent class, and then defer or override the property type in a sub class?


the things I have tried in the past:

1. there is some kind of deferred property in protocol definitions. can’t find it right now, don’t remember the name. doesn’t matter. after working with it, it was clear that it behaves in exactly the oppisite way I need.

2. I’ve written a class with every possible permutation of value type that I require. Not only is it a ton of work, but it is even more difficult to manage from the outside.

3. I am currently using the class hierarchy approach with a novel KVO hack to manage notification of changes. I define a Bool in my base class, and when my subClass’s value changes, I call self.willChangeValue(forKey: “change”) and then self.didChangeValue(forKey: “change”)… and in classes that need to know about the change, I can observe a single property. But I am still forced to write multiple lines of fragile code that test the class type and then run the exact same code…

Powered by WPeMatico

You may also like...

Comments are closed.