2015-11-04 121 views
0

我想用斯威夫特在下面的解析表中的「userVotes」列追加到一個數組 -SWIFT:解析列不追加到數組

enter image description here

這裏是我的代碼 -

import UIKit 
import Parse 

class MusicPlaylistTableViewController: UITableViewController { 

var usernames = [String]() 
var songs = [String]() 
var voters = [String]() 

var numVotes = 0 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.separatorColor = UIColor.grayColor() 

    let query = PFQuery(className:"PlaylistData") 
    query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in 

     if error == nil { 

      if let objects = objects! as? [PFObject] { 

       self.usernames.removeAll() 
       self.songs.removeAll() 
       self.voters.removeAll() 

       for object in objects { 

        let username = object["username"] as? String 
        self.usernames.append(username!) 

        let track = object["song"] as? String 
        self.songs.append(track!) 

        let title = object["userVotes"]! as? String 
        self.voters.append(title!) 
        print("Array: \(self.voters)") 

       } 

       self.tableView.reloadData() 
      } 

     } else { 

      print(error) 
     } 
    } 


} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 

} 

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // #warning Incomplete implementation, return the number of rows 
    return usernames.count 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCellWithIdentifier("CellTrack", forIndexPath: indexPath) as! TrackTableViewCell 

    //cell.username.text = usernames[indexPath.row] 
    cell.username.text = usernames[indexPath.row] 
    cell.songTitle.text = songs[indexPath.row] 
    cell.votes.text = "\(numVotes)" 

    cell.selectionStyle = UITableViewCellSelectionStyle.None 
    return cell 
} 

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 



} 


} 

我想解析陣列列追加如下 - [[ 「用戶1,」 USER5 「USER9」],[ 「用戶1,」 用戶2 「用戶3」],[ 「USER4,」 USER5, 「user6」],...]

在這一點上,我得到以下運行時錯誤 - 致命錯誤:意外發現零而展開的可選值

回答

2

自認爲是在「userVotes」每個對象是一個數組,你,你已經聲明

var voters = [String]() 

這是不正確的,因爲你說,會有一個元素被追加,而不是這種情況。

所以,你應該申報選民...

var voters = Array<Array<String>>() 

然後爲你下載它,

for object in objects { 
    let title = object["userVotes"]! as? [String] 
    self.voters.append(title!) 
    print("Array: \(self.voters)") 
} 
+0

完美,謝謝! – SB2015