簡體   English   中英

不能為“Set”類型的值添加下標<String> &#39; 帶有類型為 &#39;Int&#39; 的索引

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

我有一組字符串,其中包含一些數據。 但是當我將數據從集合顯示到 tableView 時,在 cellForRowAtIndexPath 方法中,它給了我上述錯誤。 這是我的代碼:

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
}

任何幫助都會很棒。 謝謝!

集合是不可索引的,因為集合元素的列出順序無關緊要。 您應該將元素存儲在數組或不同的數據結構中。 您可以快速執行以下操作(不推薦):

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
}

這些場景表明數據結構/算法不正確。

您需要根據您的要求將 Set 轉換為數組。 要將集合轉換為數組,

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

您可以使用 2 種方式:

  1. 數組(貿易集)[indexPath.row]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM