8
votes

After reading some posts here regarding this issue, I discovered that my protocol should inherit from 'class' in order for 'weak' to work on my delegate variable.

'weak' may only be applied to class or class-bound protocol types.

If my protocol does not inherit from 'class', does swift 'infer' that it should be weak?

Is this the de facto way for casting a variable of type 'protocol' to weak ?

What happens in terms of memory management

protocol FacebookLoginViewControllerDelegate: class {
    func facebookLoginViewControllerDidLogin(controller: FacebookLoginViewController)
}

class FacebookLoginViewController: UIViewController {

    weak var delegate: FacebookLoginViewControllerDelegate?

}
1
I'm unsure what you're asking here... Making a protocol class bound (: class) simply tells the compiler that it can only ever represent a reference type – and therefore you can use weak on it. You cannot make a value type weak, as ARC (automatic reference counting) works with references, not with values.Hamish
seems like a reasonable answer. fancy posting that as an answer ?user1951992
@robdashnash Sure thing :) I only didn't post it as an answer as I wasn't initially 100% sure what you were asking! So just to clarify, your question is basically "Do I have to make my protocol class bound in order to use weak on it?"Hamish

1 Answers

11
votes

Making a protocol class bound with : class simply tells the compiler that it can only ever represent a reference type – and you can therefore use the weak attribute on it.

If you don't mark a protocol as being class bound, then Swift will assume that it could be representing either a reference or value type. Because ARC (automatic reference counting) only works with references, and not values, then the compiler will prevent you from being able to put the weak attribute on it.

The reason that ARC doesn't work with value types is that because they get copied when you pass them around, instead of being passed around by reference. Therefore their memory can easily managed as their lifetime is super predictable, unlike reference types.

For reference types, if you're using a delegate pattern, then the delegate should always be weak in order to avoid retain cycles – and therefore the protocol should always be class bound. Using a value type for a delegate makes next to no sense, as it'll always refer to a copy of what you assigned to it.