Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert the expression's type '[AnyObject]?' to type 'NSArray'

Tags:

swift

xcode6

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?

like image 936
Reece Kenney Avatar asked Sep 27 '14 15:09

Reece Kenney


1 Answers

"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
like image 165
Maxim Shoustin Avatar answered Oct 23 '22 06:10

Maxim Shoustin