Overriding Generic Function Error in Swift

Overriding a generic function produce an error

Just remove <T> in function. Because you have T in typealias.

protocol BaseCellProtocol {
associatedtype T
func configure(with object: T?)
}

class BaseTableViewCell: UITableViewCell, BaseCellProtocol {

typealias T = String

func configure(with object: T?) {
}
}

class TableViewCell: BaseTableViewCell {

override func configure(with object: String?) {
label.text = object
}
}

error when having class method in a generic class with same name as non-generic super class

You cannot override the function since the parameter types are difference, hence, one function cannot act as the other. Also, you cannot use the same method signature, if it already exists. The only solution is to change the name, or use the same type for the parameter as the superclass. Also, you cannot hide methods in superclasses, but you could throw an exception if it is used by overriding it.

Swift: Method overriding in parameterized class

It has nothing at all to do with the generics (what you call "parameterized"). It has to do with how one function type is substitutable for another in Swift. The rules is that function types are contravariant with respect to their parameter types.

To see this more clearly, it will help to throw away all the misleading generic stuff and the override stuff, and instead concentrate directly on the business of substituting one function type for another:

class A {}
class B:A {}
class C:B {}

func fA (x:A) {}
func fB (x:B) {}
func fC (x:C) {}

func f(_ fparam : B -> Void) {}

let result1 = f(fB) // ok
let result2 = f(fA) // ok!
// let result3 = f(fC) // not ok

We are expected to pass to the function f as its first parameter a function of type B -> Void, but a function of type A -> Void is acceptable instead, where A is superclass of B.

But a function of type C -> Void is not acceptable, where C is subclass of B. Functions are contravariant, not covariant, on their parameter types.



Related Topics



Leave a reply



Submit