Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple swift delegate in swift playground

I'm very new to Swift and programming in general, a bit of Fortran 77 way back, and more recently some simple programming of microcontrollers. I'm working through the basics and all was well until i came across something that i just can't quite get to grips with - delegates. All the online posts don't quite get the concept across, at least for me, so to give myself something that i can refer back to, i've set up a basic template shown below in playground. If i run the code below it works and prints "Something done" to the terminal, but if i make the protocol a "class" protocol ie "protocol SomeDelegate: class {" and make the "var delegate" a "weak var delegate" as recommended in various posts, it doesn't 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()
like image 276
Tom Chappy Avatar asked Aug 10 '16 14:08

Tom Chappy


1 Answers

It doesn't print because the delegate is nil right after you set it. The reason for this is simple: no instance owns it (the reference count is zero). No one owns delegate because you declared it a weak property of OtherClass. Try establishing an ownership, e.g.

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

Even though delegate is weak, it will now print Something done again.

Declaring delegates as weak makes sense because it prevents circular references causing delegate to never be release in memory – that's a whole different story though – check how reference counting works, then you will understand why this is a good practice.

like image 170
ff10 Avatar answered Nov 15 '22 05:11

ff10