2016-10-27 5 views
1

キーに基づいてテーブルビューに値をプルするJSONファイルがあります。テーブルビューに値が表示されないようにしたいつまり、キーに複数回関連付けられていても、テーブル内の値は1回だけ必要です。Swift:テーブルビューで結果をフィルタリングして、JSONから重複を返さないようにします。

この特定の場合です。 JSONファイルの各エントリは、9のメディア業界のうちの1つに関連付けられています。メディア業界がすでにテーブルビューに印刷されている場合は、テーブルビューで2度目に表示したくありません。

ここに私のコードです。私は重複を避ける方法を見つけ出すことができませんでした。これは、繰り返しであってもすべての値を表示します。

func parseJSON(){ 
    do{ 
     let data = NSData(contentsOfURL: NSURL(string: "https://jsonblob.com/api/jsonBlob/580d0ccce4b0bcac9f837fbe")!) 

     let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) 

     for anItem in jsonResult as! [Dictionary<String, AnyObject>]{ 

      let mifiIndustry2 = anItem["mediaIndustry"] as! String 

      let newIndustry = Industry(industryName: mifiIndustry2) 
      industryOfMifi.append(newIndustry) 
     } 
    } 
    catch let error as NSError{ 
     print(error.debugDescription) 
    } 
} 

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

    if let cell = tableView.dequeueReusableCellWithIdentifier("IndustryCell", forIndexPath: indexPath)as? IndustryCell{ 

     let industry: Industry! 
     industry = industryOfMifi[indexPath.row] 
     cell.configureCell(industry) 
     return cell 

    } else{ 
     return UITableViewCell() 
    } 

} 

答えて

0

値を重複しているかどうかを確認するためにセットを使用します。あなたはmifiIndustry2ための変数を設定した後、セットがmifiIndustry2が含まれているかどうかを確認、

var industrySet = Set<String>() 

右:ループのために、設定を宣言し、あなたの前に

let mifiIndustry2 = anItem["mediaIndustry"] as! String 
if !(industrySet.contains(mifiIndustry2)) { 

    //if the set doesn't contain the string, add it so that you can check for it again later 
    industrySet.insert(mifiIndustry2) 

    //since it passed the check and is not a duplicate, initialize it as Industry and add to industry array 
    let newIndustry = Industry(industryName: mifiIndustry2) 
    industryOfMifi.append(newIndustry) 
} 
関連する問題