Swift:如何解决“协议”类型的弱变量非法的问题 [英] Swift: how to work around issue where weak variable of type 'protocol' is illegal

查看:711
本文介绍了Swift:如何解决“协议”类型的弱变量非法的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了有关此问题的一些帖子之后,我发现我的协议应该继承class,以便'weak'能够处理我的委托变量。



'weak'可能只适用于类或类绑定协议类型。



如果我的协议没有从'class'继承,那么swift'推断'它是应该弱吗?



这是将协议类型的变量强制转换为弱的事实上的方法吗?



会发生什么在内存管理方面

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

类FacebookLoginViewController:UIViewController {

弱var委托:FacebookLoginViewControllerDelegate?

}


解决方案

制作一个与绑定的协议类:class 只是告诉编译器它只能表示一个引用类型 - 因此你可以使用 weak b

如果你没有将协议标记为类绑定,那么Swift将假设它可能代表 引用或值类型。因为ARC(自动引用计数)仅适用于引用,而不适用于值,因此编译器将阻止您放置属性在它上面。



ARC不能使用值类型的原因是,因为它们在传递它们时会复制 ,而不是通过引用传递。因此,与引用类型不同,它们的内存可以很容易地管理,因为它们的生命周期是超可预测的。



对于引用类型,如果您使用的是委托模式,那么 delegate 应始终为 weak 以避免保留周期 - 因此协议应始终是类绑定的。使用委托的值类型几乎没有任何意义,因为它总是引用您分配给它的副本。


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.

这篇关于Swift:如何解决“协议”类型的弱变量非法的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆