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

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.


weak is a qualifier for reference types (as opposed to value types, such as structs and built-in value types).

Reference types let you have multiple references to the same object. The object gets deallocated when the last strong reference stops referencing it (weak references do not count).

Value types, on the other hand, are assigned by copy. Reference counting does not apply, so weak modifier does not make sense with them.


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.