2016-11-08 151 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) 
相关问题