0

Cyclic references getting formed in this example, however I can't apply unowned or weak to protocol variables, what's the workaround in this situation.

protocol Report {
    func done()
}

class Employee {
    unowned var report: Report? //error here with using unowned or weak

    func whenIAmDone() {
        report.done()
    }
}

class Supervisor: Report {
    var employees: [Employee]?

    init() {
        for i in 1...5 {
            var employee = Employee()
            employee.report = self
            employees?.append(employee)
        }
    }

    func done() {
        println("work done by...")
    }
}
user2727195
  • 7,122
  • 17
  • 70
  • 118

2 Answers2

1

You need to declare your Report protocol as class-only by adding class to its declaration:

protocol Report: class {
    func done()
}

You have a separate issue there, with disagreement between your choice of "weak" keywords and the report property being optional. Here's the rule: weak instances are always optional, unowned instances are never optional. Employee should look like this:

class Employee {
    weak var report: Report? //error here with using unowned or weak

    func whenIAmDone() {
        report?.done()
    }
}

or if you want report to be unowned, it would need to be a non-Optional, but then you need an initializer that can give it a value.

Nate Cook
  • 92,417
  • 32
  • 217
  • 178
0

You have to declare your protocol as class-only like below.

protocol Report : class {
    func done()
}


class Employee {
    weak var report: Report? 

    func whenIAmDone() {
        report?.done()
    }
}

Read this to learn the difference between weak and unowned. What is the difference between a weak reference and an unowned reference?

Community
  • 1
  • 1
rakeshbs
  • 24,392
  • 7
  • 73
  • 63