简体   繁体   中英

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

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.

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>()

You can do this trick:

protocol P {}

class C: P {}

class C1<T: P> {}

let c1 = C1<C>() 

In this case you wrap you class C with protocol P , then you able to create new generic class C1 where T is your protocol P . That's allow you to create instance of C1 class with generic parameter class C .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM