2016-09-30 75 views
0

我試圖在將字體發送到Post類的照片源之前將2個對象添加到字典中。這就是我所擁有的,我正在使用Firebase。將對象添加到字典

if let postDict = snap.value as? Dictionary<String, AnyObject> { 

     for(name, value) in postDict { 
      if name == "postedBy" { 

       DataService.ds.REF_USERS.child(value as! String).observeSingleEventOfType(.Value, withBlock: { (friendDictionary) in 

        let userDict = friendDictionary.value as! NSDictionary 
        value.setValue(userDict.objectForKey("username"), forKey: "username") 
        value.setValue(userDict.objectForKey("profileThumbUrl"), forKey: "profileThumbUrl") 
        self.collectionView?.reloadData() 

       }) 
      } 
     } 

     let key = snap.key 
     let post = Post(postKey: key, dictionary: postDict) 
     self.posts.append(post) 

這樣做的問題是,當我嘗試用戶的setValue(),以用戶名和profileThumbUrl增加值postDict我得到的錯誤:「這個類不是鍵值編碼兼容的關鍵用戶名。 「我在其他情況下使用這種類型的方法,所以我不知道是否因爲我在開始時使用「如果讓」,因爲我通常不會使用它。有任何想法嗎?

+0

什麼是'value'類型? – rmaddy

+0

您是否嘗試過不使用if let? –

+0

我認爲價值是任何對象 –

回答

1

objectForKey返回一個可選類型,它不符合NSDictionary,因此您需要打開可選項才能使其工作。

for(name, value) in postDict { 
     if name == "postedBy" { 

      DataService.ds.REF_USERS.child(value as! String).observeSingleEventOfType(.Value, withBlock: { (friendDictionary) in 

       let userDict = friendDictionary.value as! NSDictionary 

       guard let username = userDict.objectForKey("username") else { continue } 
       guard let profileThumbURL = userDict.objectForKey("profileThumbUrl") else { continue } 

       value.setValue(username, forKey: "username") 
       value.setValue(profileThumbUrl, forKey: "profileThumbUrl") 
       self.collectionView?.reloadData() 

      }) 
     } 
    }