hidden-username
hidden-username

Reputation: 2697

!? Strange double unwrapped optional syntax in 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

Upvotes: 1

Views: 1301

Answers (1)

matt
matt

Reputation: 535557

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?!
}

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] {

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.

Upvotes: 4

Related Questions