shahin ali agharia
shahin ali agharia

Reputation: 1639

Cannot subscript a value of type 'Set<String>' with an index of type 'Int'

I am having a Set of Strings which have some data in it. But when I was showing data from the set to the tableView, in cellForRowAtIndexPath method it gives me above stated error. Here is my Code:

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
}

Any help would be great. Thank you!

Upvotes: 4

Views: 3320

Answers (3)

user1648741
user1648741

Reputation:

you can use 2 way :

  1. Array(tradeSet)[indexPath.row]

  2. tradeSet.enumerated().first{(index , value) in index == indexPath.row}!.element

Upvotes: 0

Sealos
Sealos

Reputation: 562

A set is not indexable, because the order in which the elements of a set are listed is irrelevant. You should be storing your elements in an array or a different data structure. You could do something quick like the following (Not recommended):

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
}

These kind of scenarios suggest incorrect data structure/algorithm.

Upvotes: 2

Binesh
Binesh

Reputation: 61

You need to convert the Set to an array for your requirement. To convert a set to an array ,

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

Upvotes: 1

Related Questions