【问题标题】:Class-only generic constraints in SwiftSwift 中的纯类泛型约束
【发布时间】:2017-11-10 00:41:33
【问题描述】:

我正在尝试将泛型类型的变量标记为弱:

class X<T> {
  weak var t: T?
}

如果我不对T 设置任何约束,我会收到错误weak cannot be applied to non-class type 'T'

如果我只将它与 NSObject 派生类一起使用,这将起作用:

class X<T: NSObject> {
  weak var t: T?
}

但我也希望能够使用纯 Swift 类。

对于协议,可以通过使用 class 关键字来要求实现者是类类型:

protocol ClassType: class {
}

使用ClassType 协议,我现在可以将变量标记为弱:

class X<T: ClassType> {
  weak var t: T?
}

但我无法将class 关键字直接添加到泛型参数中:

class X<T: class> { // Compile error
  weak var t: T?
}

我可以使协议解决方案适用于所有带有扩展名的 NSObject 派生类:

extension NSObject: ClassType {
}

但是对于纯 Swift 类,没有可以添加此扩展的通用超类。有没有办法在不向我想使用X 类的每个类添加ClassType 协议的情况下完成这项工作?例如。通用参数的一些特殊限定符,例如class X&lt;T:ThisIsAClass&gt;?

【问题讨论】:

    标签: swift class generics protocols anyobject


    【解决方案1】:

    您想要AnyObject,Swift 文档将其描述为:

    所有类都隐式遵循的协议。

    class X<T: AnyObject> {
        weak var t: T?
    }
    
    class C { }
    let x = X<C>()  // works fine
    x.t = C()  
    
    // error: type 'Int' does not conform to protocol ‘AnyObject’
    // (because Int is a struct)
    let y = X<Int>()
    

    【讨论】:

    • 有没有办法让它与具有类绑定的协议一起工作? (例如能够创建protocol Interface: class { },然后创建子类class Y: X&lt;Interface&gt; { }
    • 找到答案:您需要在协议声明中添加@objc属性,它也可以正常工作@objc protocol Interface: class { }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多