2015-11-04 63 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