简体   繁体   English

如何在Swift Generic类中使用AnyClass

[英]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') 从非协议的非类型'AnyClass'(又名'AnyObject.Type')继承

Ideally I would like to use 'T' to be as a specific type rather than AnyClass, but AnyClass is OK as well. 理想情况下,我想使用'T'作为特定类型而不是AnyClass,但AnyClass也可以。

Thanks 谢谢

Instead of specifying T needs to be a class, you could instead do: 您可以改为:而不是指定T需要成为一个类:

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 : 如果你打算使用T.Type很多可能使用是值得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. 此方法的优点是T.Type可以表示结构和枚举,以及类。

You should use AnyObject if you want the type to be a class. 如果希望类型为类,则应使用AnyObject

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 . 在这种情况下,您使用协议P包装C类,然后您可以创建新的泛型类C1 ,其中T是您的协议P That's allow you to create instance of C1 class with generic parameter class C . 这允许您使用通用参数类C创建C1类的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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