UIViewController初始化方法中的隐式解包选项 [英] Implicitly Unwrapped Optionals in UIViewController init method

查看:109
本文介绍了UIViewController初始化方法中的隐式解包选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如文档所说您确定可选项确实包含值,您可以通过添加感叹号来访问其基础值(!)

那么为什么UIViewController init方法使用

So why UIViewController init method use

init(nibName nibName:String!,bundle nibBundle:NSBundle!)

告诉我如果指定nil,则nibName属性设置为nil。

为什么不使用 init(nibName nibName:String ?, bundle nibBundle:NSBundle?)而不是?

我对此非常困惑。

推荐答案

init(nibName nibName: String!,bundle nibBundle: NSBundle!)

调用Objective C框架代码。这会调用initWithNibName:bundle。您可以选择传递此方法的参数nil。目标C很好。如果在initiWithNibName中传递nil,它会尝试根据相关类的名称为您解析名称。如果传入nil for bundle,则将其替换为[NSBundle mainBundle]。

Is calling into Objective C framework code. This calls initWithNibName:bundle. You can optionally pass this method's arguments nil. Objective C is fine with that. If you pass nil in initiWithNibName it tries to resolve the name for you based on the name of the class in question. If you pass in nil for bundle it replaces this with [NSBundle mainBundle].

因此,Swift使这个参数成为可选参数。必须这样做以允许变量可选地为零。问题是为什么它不能使它成为标准的可选项并要求你明确地打开它。答案是隐式展开的可选项在将其传递给Objective C之前立即展开可选项。您不希望显式解包此问题,因为一旦您传入参数,无论是否为nil,您都已完成设置。您不希望必须显式解包它,然后将其传递给Objective C!这样做没有任何意义。

So, Swift makes this parameter an optional. It must do so to permit the variable to optionally be nil. The question is why does it not make it a standard optional and require you to explicitly unwrap it. The answer is that the implicitly unwrapped optional immediately unwraps the optional before passing it to Objective C. You don't want to have to explicitly unwrap this since once you pass your argument in, whether nil or otherwise, you are done setting it. You don't want to have to explicitly unwrap it and then pass it to Objective C! Doing so wouldn't make any sense.

这篇关于UIViewController初始化方法中的隐式解包选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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