Why does Swift reject `weak var delegate: CacheDelegate?` until the `CacheDelegate` protocol inherits from `AnyObject`?
answer
- weak needs a reference to track
- structs and enums can conform too
- class-only protocol in the inheritance list
- the deprecated older spelling
basics
~20 sA weak reference only makes sense for class instances, and a plain protocol can be adopted by structs and enums. Adding AnyObject to the protocol's inheritance list makes it class-only, so the compiler knows every conformer is a reference and accepts weak.
solid answer
~40 s`weak` and `unowned` apply only to class references, but a plain protocol can be adopted by a struct or an enum, so for `any CacheDelegate` the compiler cannot guarantee there is an object to reference weakly. It reports "'weak' must not be applied to non-class-bound 'any CacheDelegate'; consider adding a protocol conformance that has a class bound". Declaring `protocol CacheDelegate: AnyObject` makes it a **class-only protocol**: structs and enums that try to adopt it get "non-class type cannot conform to class protocol", and `weak var delegate: (any CacheDelegate)?` compiles. The older `protocol P: class` spelling still works but draws a deprecation warning recommending `AnyObject`. As a side effect, a `let` of the class-only protocol type can still have its settable properties assigned, and its requirements cannot be marked `mutating`.
code
swift · 27 linesprotocol CacheDelegate: AnyObject {
func cache(_ cache: ImageCache, didEvictKey key: String)
}
final class ImageCache {
weak var delegate: (any CacheDelegate)?
private var storage: [String: Int] = [:]
func evict(_ key: String) {
storage[key] = nil
delegate?.cache(self, didEvictKey: key)
}
}
final class GalleryViewController: CacheDelegate {
let cache = ImageCache()
init() { cache.delegate = self } // cache -> controller is weak: no cycle
func cache(_ cache: ImageCache, didEvictKey key: String) {
print("evicted \(key)")
}
}
var controller: GalleryViewController? = GalleryViewController()
let cache = controller!.cache
cache.evict("hero.png")
controller = nil
print(cache.delegate == nil)go deeper
Recall that delegate properties are usually weak, and that weak works only when the protocol inherits AnyObject so every conformer is a class.
Explain why the compiler rejects weak on a plain protocol type, quote the class-bound diagnostic, and show the AnyObject fix plus the deprecated class spelling.
Discuss the side effects of being class-only, value-type test doubles ruled out, mutating forbidden, let existentials assignable, and the property-level composition when the protocol is not yours.
Decide which protocols in a codebase model identity-bearing collaborators and make those class-only; keep data-shaped protocols open to value types rather than adding AnyObject by habit.
## The problem: `weak` needs a class The delegate pattern hands events from one object to another: an `ImageCache` tells its `delegate` when it evicts a key. The owner of the cache (say, a gallery view controller) is usually also the delegate, so a strong `delegate` property would make each object keep the other alive. The standard answer is to hold the delegate **weakly**. (Why that breaks a reference cycle, and how `weak` differs from `unowned`, is covered with ARC and retain cycles.) `weak` and `unowned` are **reference ownership modifiers**: they describe how a reference to a **class instance** is counted. A Swift protocol, by default, can be adopted by classes, structures and enumerations. A value of type `any CacheDelegate` might therefore be a struct, which has no identity and no reference count, so a weak reference to it is meaningless. The compiler refuses: ```plaintext error: 'weak' must not be applied to non-class-bound 'any CacheDelegate'; consider adding a protocol conformance that has a class bound ``` `unowned` is rejected with the equivalent message. ## The fix: a class-only protocol Add `AnyObject` to the protocol's inheritance list: ```swift protocol CacheDelegate: AnyObject { func cache(_ cache: ImageCache, didEvictKey key: String) } ``` `AnyObject` is the protocol every class type implicitly conforms to. Inheriting it makes `CacheDelegate` a **class-only protocol**, with several effects: - `weak var delegate: (any CacheDelegate)?` now compiles; the property must still have an optional type, because ARC sets it to `nil` when the object goes away. - A struct or enum that tries to adopt it fails with "non-class type 'Logger' cannot conform to class protocol 'CacheDelegate'". - `AnyObject` may sit anywhere in the inheritance list beside other protocols, as in `protocol P: AnyObject, Named`. - The older spelling `protocol CacheDelegate: class` still compiles but warns: "using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead". ## Knock-on effects of being class-only | Behaviour | Plain protocol | Class-only protocol | |---|---|---| | struct or enum conformers | allowed | compile error | | `weak` / `unowned` stored references | rejected | allowed | | assigning a `{ get set }` property through a `let` of the protocol type | rejected | allowed, the box holds a reference | | `mutating` on requirements | allowed | error: not valid in class-bound protocols | The third row follows from reference semantics: `let d: any CacheDelegate` fixes which object `d` points to, not the object's contents, so `d.name = "x"` is fine. ## When you cannot change the protocol If the protocol belongs to someone else and you only need weak storage of its class conformers, use a **composition** at the property: `weak var delegate: (any CacheDelegate & AnyObject)?`. That restricts what the property accepts without changing who may adopt the protocol. ## Mistakes that show up in review - Declaring the delegate property `weak` and then fixing the compile error by making the protocol `@objc`, which drags in Objective-C rules the code did not need. - Forgetting that `weak` alone does not make calls safe: the delegate can be `nil` at any time, so call it with optional chaining as in `delegate?.cache(self, didEvictKey: key)`. - Adding `AnyObject` to a protocol that value types already adopt, which breaks every one of them at once. ## Choosing deliberately 1. Use `AnyObject` when the protocol's behaviour **assumes reference semantics**: delegates, observers, anything stored weakly or compared by identity. 2. Do not add it reflexively: it forbids value-type conformers, which also rules out simple struct test doubles. 3. Remember that `AnyObject` is a constraint on conformers, not a guarantee of thread safety or of `Sendable`. The interview answer in one line: weak references need a class, plain protocols admit value types, and `AnyObject` in the inheritance list closes that gap.
- Why can a `let d: any CacheDelegate` still have `d.name = "x"` assigned once the protocol inherits `AnyObject`?Every conformer is now a class, so the existential holds a reference. `let` fixes the reference, not the object it points to, and a settable property on that object can be assigned. For a plain protocol the compiler must assume a value type could be inside, so the same assignment requires `var`.
- You cannot edit a third-party delegate protocol, but you need to store its conformers weakly. What do you write?Constrain the property instead of the protocol: `weak var delegate: (any TheirDelegate & AnyObject)?`. The composition accepts only class conformers, so `weak` is legal, and the protocol stays adoptable by value types elsewhere.
- weak can be applied to any optional property whatever its type.
- protocol Delegate: class is the current recommended spelling.
- A struct can adopt a class-only protocol if it holds a class property.
- Inheriting AnyObject makes the protocol and its conformers thread-safe.
- A weak delegate property can have a non-optional type.