Why can the keyword “weak” only be applied to class and class-bound protocol types

后端 未结 11 1300
清酒与你
清酒与你 2020-12-13 03:14

When I\'m declaring variables as weak in Swift, I sometimes get the error message from Xcode:

\'weak\' may only be applied to class and

相关标签:
11条回答
  • 2020-12-13 04:06

    One common reason for this error is that you have declared you own protocol, but forgot to inherit from AnyObject:

    protocol PenguinDelegate: AnyObject {
        func userDidTapThePenguin()
    }
    
    class MyViewController: UIViewController {
        weak var delegate: PenguinDelegate?
    }
    

    The code above will give you the error if you forget to inherit from AnyObject. The reason being that weak only makes sense for reference types (classes). So you make the compiler less nervous by clearly stating that the PenguinDelegate is intended for classes, and not value types.

    0 讨论(0)
  • 2020-12-13 04:07

    Just FYI and who is not updated. After swift proposal SE-0156 https://github.com/apple/swift-evolution/blob/master/proposals/0156-subclass-existentials.md was implemented, there is in the Swift docs "Class-Only Protocols section" https://docs.swift.org/swift-book/LanguageGuide/Protocols.html now described to use AnyObject instead of class. So, it is possible for : class to be deprecated in future.

    0 讨论(0)
  • 2020-12-13 04:08
    protocol PenguinDelegate: class {
        func userDidTapThePenguin()
    }
    
    class MyViewController: UIViewController {
        weak var delegate: PenguinDelegate?
    }
    

    If you type class after your protocol it works as well and seems more appropriate that for NSObjectProtocol.

    0 讨论(0)
  • 2020-12-13 04:10

    I tried to capture String and Array-typed properties for a closure. I got these errors:

    'weak' may only be applied to class and class-bound protocol types, not '[String]'

    'weak' may only be applied to class and class-bound protocol types, not 'String'

    I played a while in the playground, and it turned out, capturing self is enough for these types.

    0 讨论(0)
  • 2020-12-13 04:11

    I was using objective C class in swift for a scrolView. I created IBOutlet of that scroll view. And while compiling code this error started showing.

    So to fix this kind of issue, import that class in your bridging header

    import "YourClass.h"

    I was using Xcode 9.2 with swift 3.2

    0 讨论(0)
提交回复
热议问题