! for_in []中奇怪的双展开包装可选语法? [英] !? Strange double unwrapped optional syntax in for_in []?

查看:54
本文介绍了! for_in []中奇怪的双展开包装可选语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我有一个

Earlier I had a question that I figured out, but the answer led to another question. What is the !? syntax, I haven't seen it anywhere else, but it was the only way I could get the code to compile. Can someone tell me what "!?" the syntax means? Is it a bug? The link shows all code.

field.superview!?.superview?.layer.borderWidth = 2

推荐答案

UIAlertController的textFields属性是[AnyObject]?.所以这就是你在做什么:

A UIAlertController's textFields property is an [AnyObject]?. So this is what you are doing:

let textFields : [AnyObject]? = [UIView()] // textFields is an Optional
for field in textFields! { // you unwrap the Optional, but now...
    // ... field is an AnyObject
    let v1 = field.superview // now v1 is a UIView?!
}

您看到问题了吗? AnyObject没有superview属性-或任何其他属性. Swift会允许这样做,但只会以将结果包装在Optional中为代价,因为这可能不是UIView,所以它可能不会响应superview(正如我解释

Do you see the problem? An AnyObject has no superview property - or any other properties. Swift will allow this, but only at the expense of wrapping the result in an Optional, because this might not be a UIView and so it might not respond to superview (as I explain here). So now it calls superview for you. But superview itself yields an Optional (because, if this is a UIView, it might have no superview). Hence the double Optional.

但是,如果您从一开始就进行铸造,那将不会发生:

But if you had cast to start with, that would not have happened:

for field in textFields as [UIView] {

现在field是一个UIView,向其发送superview消息是合法的,您只需要处理每个superview的单个展开即可.

Now field is a UIView and it is legal to send it the superview message, and you just have to deal with the single unwrapping of each superview.

这篇关于! for_in []中奇怪的双展开包装可选语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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