Class-only generic constraints in Swift

前端 未结 1 1415
感动是毒
感动是毒 2020-12-29 05:44

I\'m trying to mark a variable of a generic type as weak:

class X {
  weak var t: T?
}

If I don\'t put in any constraints for

相关标签:
1条回答
  • 2020-12-29 06:25

    You want AnyObject, which the Swift docs describe as:

    The protocol to which all classes implicitly conform.

    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>()
    
    0 讨论(0)
提交回复
热议问题