为什么Swift不允许对非可选类型使用弱引用? [英] Why Swift disallows weak reference for non-optional type?

查看:76
本文介绍了为什么Swift不允许对非可选类型使用弱引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是纯粹的好奇心,我可能会误解一些关于Swift中弱引用的事情.

This is not pure curiosity, there is a feeling that I may misunderstand something about weak references in Swift.

假设我从View Controller创建一个类,并将其引用传递给初始化程序:

Suppose I create a class from a View Controller and pass its reference to the initialiser:

class = MyClass(vc: self)

由于情节提要和窗口已经保留了对该View Controller的引用,因此MyClass对其具有弱引用似乎是合乎逻辑的(出于类似的原因,默认情况下,在IB中创建的所有引用都是弱的):

Since the storyboard and window already keep a reference to this View Controller, it seems logical for MyClass to have a weak reference to it (for the similar reason all references created within IB are weak by default):

class MyClass: NSObject {
    private weak var viewController: UIViewController

    init(vc: UIViewController) {
       self.viewController = vc
       super.init
    }

    func setViewController(_ vc: UIViewController) {
       self.viewController = vc
    }

    ...
}

但是,此代码会产生编译错误,因为viewController变量不是可选的.所以我必须加'!'查看viewController声明并删除初始化程序,只留下看起来不太自然的setViewController.

However this code gives compilation error, as viewController variable isn't optional. So I had to add '!' to viewController declaration and remove the initialiser, leaving only setViewController which looks rather unnatural.

禁止非可选的弱数据的背后原因是什么?

What is the reason behind disallowing non-optional weak data?

推荐答案

weak变量的确切定义是,该变量不会增加对象的引用计数,更重要的是,对于您的问题,该变量的值取消释放引用的对象时,它将自动设置为nil.

The very definition of a weak variable is that the variable does not increase the reference count of the object and, more importantly for your question, the variable's value will automatically be set to nil when the referenced object gets deallocated.

由于变量必须允许nil值,因此它必须是可选的.这就是为什么不允许非可选的弱变量.

Since the variable must allow for a nil value, it must be optional. This is why non-optional weak variables are disallowed.

请勿将viewController声明为隐式解包(使用!).使其成为适当的可选项(使用?).

Do not declare viewController to be implicitly unwrapped (using !). Make it a proper optional (using ?).

这篇关于为什么Swift不允许对非可选类型使用弱引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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