I need to pass a type in my generic base class.
class SomeBaseClass<T: AnyClass> {
// Implementation Goes here
}
I get the following error:
Inheritance from non-protocol, non-class type 'AnyClass' (aka 'AnyObject.Type')
Ideally I would like to use 'T' to be as a specific type rather than AnyClass, but AnyClass is OK as well.
Thanks
The placeholder type T is used in the function declaration. It tells Swift that this function can find any item in any array, as long as the foundItem and items in the array are of the same type. This makes sense — you want to look for a T value in an array of T values.
Generics and Any are often used for similar purposes, yet they behave very differently. In languages without generics, you typically use a combination of Any and runtime programming, whereas generics are statically checked at compile time.
You should use AnyObject
if you want the type to be a class.
class SomeBaseClass<T: AnyObject> {
// Implementation Goes here
}
// Legal because UIViewController is a class
let o1 = SomeBaseClass<UIViewController>()
// Illegal (won't compile) because String is a struct
let o2 = SomeBaseClass<String>()
Instead of specifying T
needs to be a class, you could instead do:
class SomeBaseClass<T> {
let type: T.Type
init(type: T.Type) {
self.type = type
}
}
If you're planning to be using T.Type
a lot it may be worth using a typealias
:
class SomeBaseClass<T> {
typealias Type = T.Type
let type: Type
...
}
Some example usage:
let base = SomeBaseClass(type: String.self)
And advantage of this method is T.Type
could represent structs and enums, as well as classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With