2016-10-27 2 views
1

키를 기반으로 테이블보기로 값을 가져 오는 JSON 파일이 있습니다. 내 표보기가 아직 표에없는 경우에만 값을 표시하기를 원합니다. 즉, 키와 여러 번 연관되어 있더라도 테이블의 값을 한 번만 원할뿐입니다.Swift : 테이블보기에서 결과를 필터링하여 JSON에서 중복을 반환하지 않습니다.

이 특별한 경우. JSON 파일의 모든 항목은 9 개의 미디어 산업 중 1 개와 관련되어 있습니다. 미디어 산업이 이미 테이블 뷰에 인쇄 된 경우 테이블 뷰에서 두 번째로보고 싶지 않습니다.

여기 코드가 있습니다. 나는 중복을 방지하는 방법을 알아낼 수 없었다. 이것은 반복 일지라도 모든 값을 보여줍니다.

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>() 

오른쪽 : 루프, Set를 선언하여 전

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) 
} 
관련 문제