Add Parse array to dictionary swift

时间:2018-04-18 17:48:17

标签: arrays dictionary swift3 swift4

I have some objects in parse and I am getting the data successfully as [PFObjects]. The issue is that I am trying to add the array elements [PFObjects] to a dictionary as values. But I keep getting an empty dictionary, so the values are not added to the dictionary. The dictionary count is also 0.

This is what I tried so far:

    var postDictionary = [String:[AnyObject]]()

    query.findObjectsInBackground(block: { (posts: [PFObject]?, error:Error?) in
        if let unwrappedPosts = posts {

            for posts in unwrappedPosts {

                if let postText = posts.object(forKey: "title") as?String {

                    self.titleArray.append(postText)
                    print("count", self.titleArray.count)  // count 10

                    self.postDictionary["title"]?.append(self.titleArray as AnyObject)

                    **try to force unwrap **
                    self.postDictionary["title"]!.append(self.titleArray as AnyObject), and the app crashed

                    for (title, text) in self.postDictionary {

                        print("\(title) = \(text)")
                    }

                    print("Dictionay text count",self.postDictionary.count) // count is 0
                }

            }

        }
    })

2 个答案:

答案 0 :(得分:2)

This syntax is very confusing

self.titleArray.append(postText)
self.postDictionary["title"]?.append(self.titleArray as AnyObject)

You append a string to an array and then you are going to append the array to the array in the dictionary. I guess this is not intended.


I recommend to map the title strings and set the array for key title once

var postDictionary = [String:[String]]()

query.findObjectsInBackground(block: { (posts: [PFObject]?, error:Error?) in
    if let unwrappedPosts = posts {

        self.titleArray = unwrappedPosts.compactMap { $0.object(forKey: "title") as? String }
        self.postDictionary["title"] = self.titleArray
        for (title, text) in self.postDictionary {              
             print("\(title) = \(text)")
        }
        print("Dictionay text count",self.postDictionary.count) // count is 0    
    }        

})

Never use AnyObject if the type is more specific.

答案 1 :(得分:1)

The proper way of adding to a dictionary is using updateValue because as far as i can see that you don't have the key "title" in your dictionary and you are appending values to unknown key i guess.

This should help:

    titleArray.append(postText)

    postDictionary.updateValue(titleArray as [AnyObject], forKey: "title")

    for (key,value) in postDictionary {
        print("\(key) \(value)") 
    }

Finally this should print:

title [posts1, posts2, posts3]