Swift: how to work around issue where weak variable of type 'protocol' is illegal

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.

  • how to find the index of a character in a string from specific position
  • Crashing while trying to move UITableView rows
  • How to get last entered value in a Dictionary in Swift?
  • UITableView dynamic cell heights only correct after some scrolling
  • How to open mail app from Swift
  • Change frame programmatically with auto layout
  • 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?
    
    }
    

    Solutions Collect From Internet About “Swift: how to work around issue where weak variable of type 'protocol' is illegal”

    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.