Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AnyClass in Swift Generic class

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

like image 765
Peymankh Avatar asked Sep 05 '15 17:09

Peymankh


People also ask

What is T type Swift?

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.

What is the difference between any and generic in Swift?

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.


2 Answers

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>()
like image 131
hennes Avatar answered Nov 12 '22 04:11

hennes


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.

like image 37
ABakerSmith Avatar answered Nov 12 '22 06:11

ABakerSmith