599

weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.

This code gives a compile error (weak cannot be applied to non-class type MyClassDelegate):

class MyClass {
  weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate {
}

I need to prefix the protocol with @objc, then it works.

Question: What is the 'pure' Swift way to accomplish a weak delegate?

Cœur
  • 37,241
  • 25
  • 195
  • 267
hnh
  • 13,957
  • 6
  • 30
  • 40

8 Answers8

1131

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

Michal Šrůtek
  • 1,647
  • 16
  • 17
flainez
  • 11,797
  • 1
  • 18
  • 16
  • 26
    My problem with this solutions is that calling the delegate causes a crash - EXC_BAD_ACCESS (as noted by others elsewhere). This seems to be bug. The only solution I have found is to use @objc and eliminate all Swift data types from the protocol. – Jim T Jul 03 '14 at 22:32
  • 12
    What's the correct way of doing weak delegates now in Swift? Apple documentation is not showing or declaring the delegate as weak in their example code: https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Protocols.html – C0D3 Dec 01 '14 at 22:13
  • @JimT, does this still give you a crash? You comment had a lot of upvotes but I am wondering if this was just in old versions of Swift. I've never gotten a crash with Swift 2 or 3. – Suragch Feb 11 '17 at 09:47
  • re: "only on classes and no other stuff like enums or structs" anyone know what the proper term for "stuff" is? types? – adamF Mar 05 '17 at 20:02
  • @adamF maybe value types? – Andrew Johnson Jul 29 '17 at 16:59
  • 2
    This is not always safe - remember that you only need to make the delegate weak if it also holds a reference to the delegator & you need to break that strong reference cycle. If the delegate holds no reference to the delegator, the delegate can go out of scope (because it's weak) and you'll have crashes and other problems :/ something to keep in mind. – Trev14 Aug 07 '18 at 21:45
  • 5
    BTW: I think the "new style" (Swift 5) is to do `protocol ProtocolNameDelegate: AnyObject`, but doesn't matter. – hnh Apr 30 '19 at 13:06
  • 1
    It should be `AnyObject` since `class` will be deprecated at some point. – José May 28 '19 at 12:31
  • 1
    @C0D3 actually it does in the link you've proviced. Maybe because currently it is 2021... but just search the line ```weak var delegate: DiceGameDelegate?``` – Mykhailo Lysenko Jun 23 '21 at 12:00
324

Supplemental Answer

I was always confused about whether delegates should be weak or not. Recently I've learned more about delegates and when to use weak references, so let me add some supplemental points here for the sake of future viewers.

  • The purpose of using the weak keyword is to avoid strong reference cycles (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.

  • You only need to use weak if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong reference cycles.

  • weak references are always optional (otherwise you would used unowned) and always use var (not let) so that the optional can be set to nil when it is deallocated.

  • A parent class should naturally have a strong reference to its child classes and thus not use the weak keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the weak keyword.

  • weak should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to this question for more on this.

  • As a general rule, delegates should be marked as weak because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends. (But see this, too.)

  • Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list. (In the past you did this using the class keyword, but AnyObject is preferred now.)

    protocol MyClassDelegate: AnyObject {
        // ...
    }
    
    class SomeClass {
        weak var delegate: MyClassDelegate?
    }
    

Further Study

Reading the following articles is what helped me to understand this much better. They also discuss related issues like the unowned keyword and the strong reference cycles that happen with closures.

Related

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 5
    This is all nice and interesting, but is not really related to my original question - which is neither about weak/ARC itself nor about why delegates are usually weak. We already know about all that and just wondered *how* you can declare a weak protocol reference (answered perfectly well by @flainez). – hnh Jan 02 '16 at 14:31
  • 33
    You're right. I actually had the same question as you earlier, but I was missing a lot of this background information. I did the above reading and made the supplemental notes to help myself understand all the issues related to your question. Now I think I can apply your accepted answer and know why I'm doing it. I hope maybe it will help future viewers as well. – Suragch Jan 02 '16 at 14:42
  • 5
    But can i have a weak protocol that does NOT depend on the type? A protocol by its self does not care what object is conforming to itself. So both a class, or a struct can conform to it. Is it possible to still have the benefit of both being able to conform to it, but only have the class types that conform be weak? – Just a coder Jul 06 '16 at 16:34
  • > because most delegates are referencing classes that they do not own I would rewrite this as: most delegators. Otherwise the non owned object becomes the owner – Victor Jalencas Feb 11 '20 at 11:18
  • what if I have one class and one struct that needs to implement the same delegate protocol. then, I can't conform the protocol to AnyObject, right? – Aswath Feb 02 '23 at 09:15
40

AnyObject is the official way to use a weak reference in Swift.

class MyClass {
    weak var delegate: MyClassDelegate?
}

protocol MyClassDelegate: AnyObject {
}

From Apple:

To prevent strong reference cycles, delegates should be declared as weak references. For more information about weak references, see Strong Reference Cycles Between Class Instances. Marking the protocol as class-only will later allow you to declare that the delegate must use a weak reference. You mark a protocol as being class-only by inheriting from AnyObject, as discussed in Class-Only Protocols.

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-ID276

Tim Chen
  • 1,364
  • 12
  • 14
  • 8
    Interesting. Is `class` deprecated in Swift 4.1? – hnh Feb 19 '18 at 15:21
  • @hnh You can still make a "pseudo-protocol" by making it a class, but protocol: AnyObject does exactly what the OP is asking for with less side effects than making it a class. (you still can't use such a protocol with value types, but declaring it a class won't solve that either) – Arru Oct 04 '18 at 11:54
8

Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.

Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.

William Rust
  • 640
  • 8
  • 7
  • As mentioned this is IMO not an answer to the question. A plain Swift program should be able to stand on it's own w/o being tied to NS'ism (this might imply not using delegate's anymore but some other design construct). My pure Swift MyClass actually doesn't care whether the destination is a struct or object, nor do I need optionals. Maybe they get to fix it later, it's a new language after all. Possibly something like 'class protocol XYZ' if reference semantics are required? – hnh Jun 07 '14 at 11:40
  • 4
    I think it's also worth noting that \@objc has additional side effects - the NSObjectProtocol suggestion of @eXhausted is a little better. With \@objc - if the class delegate takes an object argument, like 'handleResult(r: MySwiftResultClass)', the MySwiftResultClass now needs to inherit from NSObject! And presumably it's not namespace'd anymore either, etc. In short: \@objc is a bridging feature, not a language one. – hnh Jun 07 '14 at 11:46
  • I think they have resolved this. You now write: protocol MyClassDelegate : class { } – user3675131 Sep 13 '14 at 10:07
  • Where is the documentation on this? Either I'm blind or doing something wrong, because I can't find any information about this... O_O – BastiBen Oct 28 '14 at 11:04
  • I'm not sure if it answers the OP's question or not, but this is helpful especially if you are interoperating with Objc-C ;) – Dan Rosenstark Jun 20 '16 at 22:27
1

The weak qualifier only applies to reference objects. Unless you add the @objc, AnyObject, or class qualifier on your protocol, the object conforming to the protocol might not be a reference object.

Thus you need on of those qualifiers (and AnyObject is recommended, since class is expected to be deprecated.)

By the way, note that adding @objc to your classes and properties is sometimes required, even in "pure Swift" applications. It doesn't have to do with you development language. It causes the compiler to build your code in a way that is compatible with the Objective-C runtime, which is required for some OS interfaces (target/action and old-style key paths for example)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0
protocol MyProtocol {
    func doSomething()
}

class MyClass: MyProtocol {
    func doSomething() {
        print("Doing something")
    }
}

var weakProtocol: Weak<MyProtocol>?
let myObject = MyClass()
weakProtocol = Weak(myObject)
weakProtocol?.doSomething() // Will print "Doing something"
  • 1
    I've never seen Weak as part of the default Swift language, is this part of some library? If so can you also add that to your answer. – Robin Jan 24 '23 at 13:32
-1

protocol must be subClass of AnyObject, class

example given below

    protocol NameOfProtocol: class {
   // member of protocol
    }
   class ClassName: UIViewController {
      weak var delegate: NameOfProtocol? 
    }
Community
  • 1
  • 1
-9

Apple uses "NSObjectProtocol" instead of "class".

public protocol UIScrollViewDelegate : NSObjectProtocol {
   ...
}

This also works for me and removed the errors I was seeing when trying to implement my own delegate pattern.

rosem
  • 1,311
  • 14
  • 19
  • 5
    Not relevant for the question, this question is about building a pure Swift class (specifically *no* NSObject) supporting a delegate object. It is not about implementing Objective-C protocols, which is what you are doing. The latter requires @objc aka NSObjectProtocol. – hnh Apr 19 '16 at 17:03
  • OK, but not be recommended. – DawnSong Aug 17 '16 at 08:48