i'm trying call static method in base class generic subclass. see simplified playground code below.
calling non-static 'dump' function works. similar static call fails. various attempts typecast array fail.
in full production code, "classa" in 3rd-party module , can't changed. can further subclassed , extended.
does swift offer magical typecast have classt call classa.dump() directly?
class classt<t> { var dict=[string:t]() func add(key:string, obj:t) { dict[key]=obj let arr=array(dict.values) dump(arr) // works -> not expected, see comment below !!! classa.dump(arr) // error: cannot convert value of type 'array<t>' expected argument type '[classa]' classa.dump(arr as! [classa]) // error: cannot convert value of type 'array<t>' type '[classa]' in coercion classa.dump(arr as! [anyobject]) // error: 'anyobject' not subtype of 't' classa.dump(arr as! [any]) // error: 'any' not subtype of 't' } } class classa { func dump(arr:[classa]) { classa.dump(arr) } static func dump(arr:[classa]) { print(arr) } } class classb:classa { static let o=classt<classa>() func test() { classb.o.add("elem1", obj:self) } }
you have add constraint specify t
derives classa
.
class classt<t: classa> { var dict = [string : t]() func add(key: string, obj: t) { dict[key] = obj let arr = array(dict.values) //probably unecessary dump(arr) // works classa.dump(arr) } //...
without it, compiler has no way enforce conforming types t
castable classa
.