2016-11-08 65 views
1

我有一組字符串,其中包含一些數據。 但是,當我顯示的數據從設置到tableView,在cellForRowAtIndexPath方法,它給了我上述的錯誤。 這裏是我的代碼:不能使用類型'Int'的索引對'Set <String>'類型的值進行下標

var tradeSet: Set<String> = ["TKAI", "YNDX", "PSTG"] 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("MyTrade", forIndexPath: indexPath) as! MyTradeTableViewCell 

    let objects = tradeSet[indexPath.row] 
    cell.tradeName.text = objects 

    return cell 
} 

任何幫助將是偉大的。謝謝!

+4

「集合」是一種無序的集合類型,不能通過索引對其進行下標。 – vadian

+1

你必須將set轉換爲數組。 –

+1

@vadian Well *技術上*它可以通過索引下標,只是一個'SetIndex',而不是'Int';) – Hamish

回答

1

一個集合不是可索引,因爲集合中元素的排列順序是不相關的。您應該將您的元素存儲在一個數組或不同的數據結構中。你可以像下面那樣做一些事情(不推薦):

var tradeSet: Set<String> = ["TKAI", "YNDX", "PSTG"] 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("MyTrade", forIndexPath: indexPath) as! MyTradeTableViewCell 

    // This is not the best data structure for this job tho 
    for (index, element) in tradeSet.enumerated() { 
     if row == index { 
      cell.tradeName.text = element 
     } 
    } 

    return cell 
} 

這些情況表明不正確的數據結構/算法。

+3

*「一個集合不可索引,因爲它沒有順序」* - 這是錯誤的或至少是誤導性的。一個'Set'是一個集合,每個元素都有一個索引並且可以被下標。一組中元素的順序*未指定。* –

+0

@MartinR編輯。謝謝。 – Sealos

0

您需要將Set轉換爲適合您需求的陣列。 要將一個集合轉換爲一個數組,

var tradeSet: Set<String> = ["TKAI", "YNDX", "PSTG"]  
let stringArray = Array(tradeSet) 
相關問題