Upon revisiting some code that seemed to work with Xcode6 beta 5, I noticed that I am getting a "Cannot convert the expression's type '[AnyObject]?' to type 'NSArray'" error for this line:
let textFields:NSArray = loginAlert.textFields as NSArray
Here is the section of code that appears to be the problem:
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() == nil{
var loginAlert:UIAlertController = UIAlertController(title: "Sign Up / Login", message: "Please sign up or login", preferredStyle: UIAlertControllerStyle.Alert)
loginAlert.addTextFieldWithConfigurationHandler({
textfield in
textfield.placeholder = "Your username"
})
loginAlert.addTextFieldWithConfigurationHandler({
textfield in
textfield.placeholder = "Your password"
textfield.secureTextEntry = true
})
loginAlert.addAction(UIAlertAction(title: "Login", style: UIAlertActionStyle.Default, handler: {
alertAction in
let textFields:NSArray = loginAlert.textFields as NSArray
let usernameTextfield:UITextField = textFields.objectAtIndex(0) as UITextField
let passwordTextfield:UITextField = textFields.objectAtIndex(1) as UITextField
}))
}
Any ideas what the issue is?
"Cannot convert the expression's type '[AnyObject]?' to type 'NSArray'"
Sounds like loginAlert.textFields
is defined as Optional and might be nil
therefore if you are sure that its not nil
- unwrap it first by using !
:
loginAlert.textFields as AnyObject! as NSArray
or:
loginAlert.textFields! as NSArray
Pretty basic example in playground:
var temp:Array<String>? // define Optional array
temp = Array<String>() // well, we create new Array but since its optional we need set "!" each time during manipulation
temp!.append("val1") // 1st off we unwrap it and add new value
var newArray = temp as AnyObject! as Array<String> // to downcast to Array<String>, we unwrap it with AnyObject! first
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