简体   繁体   中英

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.

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?

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM