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?
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()
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With