Swift隐式转换类型(Swift implicit conversion of type)

编程入门 行业动态 更新时间:2024-10-24 15:12:38
Swift隐式转换类型(Swift implicit conversion of type)

假设我已经将UIViewController声明为我班级中的属性。 在某些情况下,我们可以隐式地将UINavigationController分配给该属性。

UIViewController *someNavigationController

在Objective-C中,我可以简单地分配

UIViewController *vc = self.someNavigationController; if (vc) { //then do something }

正如我在Swift中所理解的,如果我的self.centerViewController声明为UIViewController我应该做这样的事情。 对

let nvc = self.centerViewController as! UINavigationController

Alos我怎么检查

if nvc != nil

它说它不能为零。

Let's say I've declared UIViewController as a property in my class. In some cases we can implicitly assign UINavigationController to this property.

UIViewController *someNavigationController

In Objective-C I can simple assign

UIViewController *vc = self.someNavigationController; if (vc) { //then do something }

As I understood in Swift I should do something like this if my self.centerViewController declared as UIViewController. Right

let nvc = self.centerViewController as! UINavigationController

Alos how can I check

if nvc != nil

It says that it can't be nil.

最满意答案

as! UINavigationController as! UINavigationController意味着它是一个强制向下转换:它已被解包,它不再是一个可选的,因此它不能再为零 - 如果它零(或不可向下转换),它将会崩溃应用程序。

你可以使用可选的绑定来代替:

if let nvc = self.centerViewController as? UINavigationController { // here, nvc is not nil and is a UINavigationController, you can use it } else { // here, either self.centerViewController is nil or we can't cast it as a UINavigationController }

as! UINavigationController means it's a forced downcast: it has been unwrapped, it's no longer an Optional, therefore it can't be nil anymore - and if it were nil (or not downcastable), it would have crashed the app.

You could use optional binding instead:

if let nvc = self.centerViewController as? UINavigationController { // here, nvc is not nil and is a UINavigationController, you can use it } else { // here, either self.centerViewController is nil or we can't cast it as a UINavigationController }

更多推荐

本文发布于:2023-08-01 03:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1352816.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   隐式   Swift   type   conversion

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!