2016-10-17 31 views
0

我在下面的代码中错误地使用了下标,对于此Firebase数据拉取,但我无法弄清楚我做错了什么。我得到一个let uniqueID = each.value["Unique ID Event Number"] as! Int行不明确使用下标的错误。模糊使用下标(Swift 3)

// Log user in 
if let user = FIRAuth.auth()?.currentUser { 

     let uid = user.uid 
     // values for vars sevenDaysAgo and oneDayAgo set here 

     ... 

     let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)") 
      historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in 

       if (snapshot.value is NSNull) { 
        print("user data not found") 
       } 
       else { 

        if let snapDict = snapshot.value as? [String:AnyObject] { 

         for each in snapDict { 

          // Save the IDs to array. 
          let uniqueID = each.value["Unique ID Event Number"] as! Int 
          self.arrayOfUserSearchHistoryIDs.append(uniqueID) 
         } 

        } 
        else{ 
         print("SnapDict is null") 
        } 
       } 
     }) 
} 

我试图将我从这个post教训,但我想不出我缺少什么,因为我以为我是让编译器知道它是与“为何种类型的字典的?[字符串:AnyObject]“

任何想法或想法将不胜感激!

回答

3

我最喜欢处理数据的方式是尽可能迟的解开FIRDataSnapshot

ref!.observe(.value, with: { (snapshot) in 
    for child in snapshot.children { 
     let msg = child as! FIRDataSnapshot 
     print("\(msg.key): \(msg.value!)") 
     let val = msg.value! as! [String:Any] 
     print("\(val["name"]!): \(val["message"]!)") 
    } 
}) 
+0

感谢您的想法的火花。一旦我以这种方式重新工作,就像魅力一样工作。将分开作出回答,以便其他人可以看到他们是否遇到同样的问题。 – Ben

0

考虑到弗兰克的反馈,以下是我使用的实际工作代码,它遵循该方法,以防万一它有帮助。

// Log user in 
if let user = FIRAuth.auth()?.currentUser { 

    let uid = user.uid 
    // values for vars sevenDaysAgo and oneDayAgo set here 

    ... 

    let historyRef = self.ref.child("historyForFeedbackLoop/\(uid)") 
     historyRef.queryOrdered(byChild: "Unix Date").queryStarting(atValue: sevenDaysAgo).queryEnding(atValue: oneDayAgo).observeSingleEvent(of: .value, with: { snapshot in 

      if (snapshot.value is NSNull) { 
       print("user data not found") 
      } 
      else { 

       for child in snapshot.children { 

        let data = child as! FIRDataSnapshot 
        let value = data.value! as! [String:Any] 
        self.arrayOfUserSearchHistoryIDs.append(value["Unique ID Event Number"] as! Int) 
       } 
      } 
    }) 
}