so I have this challenge that keeps coming up. I solve it each time, but it's messy. I'd like to do it better.
my classes derive from a protocol OR a superClass, but in this case it's a protocol.
and the reason I have a hierarchy at all is that the classes have to handle different data similarly.
so one of the central methods of the class (this is a for instance) is a method that converts the class's internal type to another type.
func convert()->String
a sibling class might need a similar method, but with a different return type:
func convert()->Int
these classes are required to have a common ancestor (because their instances will eventually be in the same array.)
But, I cannot define the 'convert' method in the protocol or the superclass, such that code addressing as yet unidentified specific type as it's superclass, can simply call the method:
let myVar = classInstanceTreatedAsProtocolOrSuperClass.convert()
I am instead, forced to do a switch:
switch superClassObject{
case is ClassType:
let myLet = (superClassObject as! ClassType).convert()
whole list of things to do once we get that value
case is OtherClassType:
all of literally the same code pattern with the potential for slight differences due to type.
...
}
at times like this, with the Overabundance of required if and if let statements just to get through this, Swift goes from fun, to nightmarishly wordy.
I would like to define, in my protocol, a method that defers the return type, but sets up teh method name, so that classes the partake of my protocol, can be expected to support that method. I don't think that's possible in swift. it may conflict with some of the behavior already in place... but I thoought I'd ask. It's no fun writing War and Peace, over and over again.