startupthekid startupthekid - 1 year ago 60
Swift Question

Swift protocol & weak references with class

If I have a protocol:

protocol SomeProtocol {
func doSomething()

and in a helper class, I have a reference to a protocol variable:

class someClass {
var delegate: SomeProtocol?

isn't marked with
: class
, it's assumed that
can be anything and in the case of value types (structs and enums) there's no need for
weak var
because value types can't create strong references. In fact, the compiler doesn't allow
weak var
on anything but class types.

However, nothing stops you from setting a class as the delegate and if the protocol isn't marked with
: class
SomeProtocol is),
weak var` can't be used and that creates a retain cycle.

class MyClass: NSObject, SomeProtocol {
func doSomething() { }

struct MyStruct: SomeProtocol {
func doSomething() { }

let someClass = SomeClass()
let myStruct = MyStruct()
someClass.delegate = myStruct
// After myStruct gets assigned to the delegate, do the delegate and the struct refer to the same instance or does the struct get copied?D

let myClass = MyClass()
someClass.delegate = myClass // can't use weak var so myClass is retained

Given the above example, in the case of using delegates and datasource, shouldn't
: class
always be used? Basically any protocol that is used to maintain a reference should always be restricted to class objects right?

Answer Source

Right. If you a are trying to break retain cycle with weak reference, you have to use classes because weak modifier works only with reference types (classes).