Simple quick delegate in a fast playing field

I am very new to Swift and programming in general, a bit back from Fortran 77, and more recently about some simple microcontroller programming. I work on the basics, and everything was fine until I came across something that I just can not handle - with delegates. All online posts do not quite understand the concept, at least for me, so in order to give me something that I can return to, I installed the basic template shown below on the playground. If I run the code below, it works and prints "Something done" with the terminal, but if I make the protocol a "cool" protocol, that is, "protocol SomeDelegate: class {", and make "var delegate" a "weak delegate var" as recommended in various posts, this does not work - what am I doing wrong?

import UIKit protocol SomeDelegate { func DoSomething() } class MyViewcontroller: UIViewController, SomeDelegate { func DoSomething() { print("Something done") } } class OtherClass { var delegate: SomeDelegate? func DoSomething() { delegate?.DoSomething() } } var myVar = OtherClass() myVar.delegate = MyViewcontroller() myVar.DoSomething() 
+5
source share
1 answer

It does not print because the delegate is zero after setting it. The reason for this is simple: no instance owns it (the reference count is zero). No one owns a delegate because you declared it a weak OtherClass property. Try setting ownership, for example

 var myVar = OtherClass() let viewController = MyViewController() myVar.delegate = viewController 

Although the delegate is weak, it will print Something done again.

Declaring delegates as weak makes sense because it prevents the distribution of circular links, as a result of which the delegate will never be issued in memory - which is a completely different story - check how link counting works, then you will understand why this is good practice.

+3
source

All Articles