2016-05-12 67 views
0

我有一個tableview,要根據數據源標識符顯示不同的UITableViewCell's如何在運行時更改變量類型

這裏是我的代碼:

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

    var cell : AnyObject 

    var itemDic = items.objectAtIndex(indexPath.row) as! [String : String]; 

    switch itemDic["celltype"]! as String { 
    case "dash": 

     cell = tblGraphs.dequeueReusableCellWithIdentifier("DashboardCell") as! DashboardTableViewCell 
     cell.setData(itemDic, indexPath: indexPath) 
    case "chart": 

    cell = tblGraphs.dequeueReusableCellWithIdentifier("ChartCell") as! ChartTableViewCell 

    default: 

     cell = tblGraphs.dequeueReusableCellWithIdentifier("DashboardCell") as! DashboardTableViewCell 

    } 


    return cell 
} 

當然是給我的錯誤:

enter image description here

如何解決這個任何線索?

+1

我可能會錯過一些東西,但爲什麼不是'var cell:UITableViewCell'來代替? – Amadan

回答

0

更換

var cell : AnyObject 

var cell : UITableViewCell! 

否則它不知道你在試圖返回一個UITableViewCell

0

型anyobject類型實際上已經採取了電池的可變但方法返回UITableViewcell的一個對象。 如果你有不同類型的單元格比你不得不採用那個類型爲「UITableViewcell」的變量,它就像這個方法中的任何對象一樣工作。