Proposal: allow developer override property with new type

Proposal: when the new type can be cast to the original type, allow the child class to override the parent class property to the new type

For example, the objectValue of AppKit‘s NSTableCellView is Any?, if I write a new subclass and override objectValue to the type I want, I can reduce the amount of "as? NewType" in my code.

Now this override will report an error:

Property 'objectValue' with type 'NewType' cannot override a property with type 'Any?'

Bad side effect: if the outside world uses the cell directly as an NSTableCellView and sets the objectValue to any other type of object, it will crash when I access an overridden property, so my proposal also includes adding a new keyword "unsafeOverride" for the developer, such as "as!", if the developer can guarantee that the above situation will not occur, they will be able to use this new keyword to achieve the effect they want. Or don't use this keyword, we can specify that this kind of override must be using a Optional type, and then the compiler will automatically cast it for us, return nil if it doesn't work.

PS: I know I can add a new computational property of type NewType and cast objectValue internally, but there are actually a lot of properties are marked as Any? in AppKit, and it's always strange to write a new computational property every time, or worse, cast them everywhere into the type I want.

Looking forward to your reply, it will be great to override objectValue to the type I want. Thanks!

Have you tried not overriding but just creating another objectValue: NewType? property? An overload may do what you need. I typically just create another property (`newTypeValue: NewType?) with the proper type.

In any case I'm not sure your suggestion is feasible since the type system requires subclasses to be substitutable for their superclass. If you could override a property with a different type that would no longer be possible.

2 Likes

Thanks for your reply. I try to remove the keyword "override" and Xcode report the same error

Yes, and my proposal is limit to: When the new type can be cast to the original type, allow the child class to override the parent class property to the new type