2014-09-27 12 views
17

Dopo aver rivisitato un codice che sembrava funzionare con Xcode6 beta 5, ho notato che sto ottenendo un "Impossibile convertire il tipo di espressione" [AnyObject]? " digitare "Errore 'NSArray' per questa linea:Impossibile convertire il tipo dell'espressione '[AnyObject]?' per digitare 'NSArray'

let textFields:NSArray = loginAlert.textFields as NSArray 

Ecco la sezione di codice che sembra essere il problema:

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    
     })) 
} 

Tutte le idee che il problema è?

+2

Hai provato: 'loginAlert.textFields come ANYOBJECT! come NSArray' –

risposta

31

"Impossibile convertire il tipo di espressione '[AnyObject]?' digitare 'NSArray'"

Suona come loginAlert.textFields è definita come opzionale e può essere nil quindi se si è sicuri che la sua non nil - scartarlo prima utilizzando !:

loginAlert.textFields as AnyObject! as NSArray 

o:

loginAlert.textFields! as NSArray 

esempio Piuttosto semplice in gioco terra:

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 
+0

Grazie mille! Questo ha risolto il mio problema! Grazie anche per la spiegazione, molto apprezzata! –

Problemi correlati