2015-06-18 12 views
20

sto cercando di memorizzare il numero di risultati da una query in un numero intero in modo che possa utilizzarla per determinare il numero di righe in una tabella. Tuttavia, sto ottenendo il seguente errore: Variable 'numberOfGames' captured by a closure before being initialized' sulla linea query.findObjectsInBackgroundWithBlock{.variabile catturato dalla chiusura prima di essere inizializzato

Ho anche ricevuto un altro errore Variable 'numberOfGames' used before being initialized sulla riga return numberOfGames.

Ecco la funzione che contiene i due errori:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    { 
     var user: PFUser! 

     var numberOfGames: Int 

     //...query code....removed to make it easier to read 

     var query = PFQuery.orQueryWithSubqueries([userQuery, userQuery2, currentUserQuery, currentUserQuery2]) 
     query.findObjectsInBackgroundWithBlock{ 
      (results: [AnyObject]?, error: NSError?) -> Void in 

      if error != nil { 
       println(error) 
      } 

      if error == nil{ 

       if results != nil{ 
        println(results) 
        numberOfGames = results!.count as Int 
       } 
      } 
     } 
     return numberOfGames 
    } 

risposta

23

È necessario inizializzare la variabile prima di utilizzarla all'interno di una chiusura:

As per apple documentation

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values. You also cannot use the implicit self property, or call any of the instance’s methods.

Il comando var numberOfGames: Int appena dichiarano per inizializzare è possibile utilizzare var numberOfGames = Int() o var numberOfGames:Int = 0

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    { 
     var user: PFUser! 
     var numberOfGames:Int = 0 
     var query = PFQuery.orQueryWithSubqueries([userQuery, userQuery2, currentUserQuery, currentUserQuery2]) 
     query.findObjectsInBackgroundWithBlock{ 
      (results: [AnyObject]?, error: NSError?) -> Void in 
      if error != nil { 
       println(error) 
      } 
      if error == nil{ 
       if results != nil{ 
        println(results) 
        numberOfGames = results!.count as Int 
       } 
      } 
     } 
     return numberOfGames 
    } 
+0

* facepalm ... Ho bisogno di imparare la differenza tra dichiarazione e l'inizializzazione. Grazie per l'aiuto! – winston