Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not find member in closure

Tags:

ios

swift

I have the following code. prompt being a UIAlertController.

self.presentViewController(prompt, animated: true, completion: {
     prompt.textFields[0].becomeFirstResponder()
})

But it gives me this error: Could not find member 'becomeFirstResponder'.

Yet, if I put this in it works fine:

self.presentViewController(prompt, animated: true, completion: {
     let foo = 0
     prompt.textFields[0].becomeFirstResponder()
})

Why does the error go away when I add in a useless line of code such as the above?

like image 805
BytesGuy Avatar asked Jun 04 '14 20:06

BytesGuy


1 Answers

According to the Swift Programming Language book section on If Statements and Forced Unwrapping,

“You can use an if statement to find out whether an optional contains a value. If an optional does have a value, it evaluates to true; if it has no value at all, it evaluates to false. Once you’re sure that the optional does contain a value, you can access its underlying value”

UIAlertController doesn't have to have textFields, so because the textFields array is optional, you have to unwrap it before you can call functions on the objects inside of the array, so it should look something like this:

self.presentViewController(prompt, animated: true, completion: {
    if let textFields = prompt.textFields {
       textFields[0].becomeFirstResponder()
    }
})
like image 140
johnnyclem Avatar answered Nov 13 '22 18:11

johnnyclem