Wayne Filkins Wayne Filkins - 2 months ago 14
Swift Question

Adding objects to a dictionary

I am trying to add 2 objects to a dictionary before sending it to a Post class for a photo feed. This is what I have, I am using 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)


The problem with this is that when I try to user setValue() to add username and profileThumbUrl to value in postDict I get the error: "this class is not key value coding-compliant for the key username." I have used this type of method in other situations so I don't know if it's because i'm using "if let" at the beginning because I don't normally use that. Any ideas?

Answer

objectForKey returns an optional type, which is not compliant for an NSDictionary, so you need to unwrap the optional for this to work.

Eg

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

             })
         }
     }
Comments