如何过滤JSON数据然后枚举过滤后的数据?

时间:2016-07-27 02:17:12

标签: ios swift filter

我目前正在创建一个使用"定时奖励"只持续一段特定时间,我在Swift中使用过滤器的新手,我需要满足的当前目标:

  1. 如果redemptionDate为NULL,则显示奖励

  2. 如果currentDateTime> = redemptiondate + redeemTimeLimit(这些是JSON对象),则隐藏奖励

  3. 如果currentDateTime<显示奖励并显示倒数计时器redemptiondate + redeemTimeLimit

  4. 倒计时器金额是redemptiondate + redeemTimeLimit和currentDateTime之间的差异

  5. 到目前为止,这是我的代码,我遇到了几次崩溃,这些注释都在代码中。我也编号了我尝试并符合上述标准的区域:

       var rewardsArray : [MemberRewardsInfo] = []//MemberRewarsInfo is a JSON Object custom class
      var timeFilteredRewardsArray : [MemberRewardsInfo] = []
    
     RewardManager.sharedInstance.updateRewards({ rewards in
    
    self.timeFilteredRewardsArray = rewards
    
    
      //.1
      self.timeFilteredRewardsArray = self.timeFilteredRewardsArray.filter ({$0.redemptionDate == nil})
    
    
    for filteredReward in self.timeFilteredRewardsArray {
    
    
      let Date = NSDate()
      let df = NSDateFormatter()
      df.timeZone = NSTimeZone(forSecondsFromGMT: 0)
      df.dateFormat = "MM-dd-yyyy"
      let currentDate = df.stringFromDate(Date)
    
      //.2
      if currentDate >= filteredReward.redemptionDate! + filteredReward.redeemTimeLimit! {
    
                //remove current reward from array, not sure how to do this
    
        //.3
      } else if currentDate < filteredReward.redemptionDate! + filteredReward.redeemTimeLimit!{
    
        //.4
        var countdownTimer = (filteredReward.redemptionDate! + filteredReward.redeemTimeLimit!) - currentDate
    
           //error occurs here: "Binary operator '-' cannot be applied to two 'String' operands"
      }
    }
    
    
    
       self.rewardsArray =  self.timeFilteredRewardsArray
        self.rewardsTableView.reloadData()
    
      })
    

1 个答案:

答案 0 :(得分:0)

我建议您使用此库SwiftyJSON。 Swift对类型非常严格,JSON并不关心类型。此外,链接变得一团糟,SwiftyJSON修复了所有这些。它将帮助您专注于过滤器,因为您正在过滤数组,然后将其分配给相同的数组...

快速举例,因为我不知道你的json结构:

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["data"]["date"].string {
  //convert to date and do your filters
}