将解析数组添加到字典 swift



我在解析中有一些对象,我成功地以[PFObjects]的形式获取数据。问题是我正在尝试将数组元素 [PFObjects] 作为值添加到字典中。但是我一直得到一个空字典,所以这些值不会添加到字典中。字典计数也是 0。

这是我到目前为止尝试过的:

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

这种语法非常混乱

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

将字符串附加到数组,然后将数组附加到字典中的数组。我想这不是故意的。


我建议map title字符串并为键title设置一次数组

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

如果类型更具体,切勿使用 AnyObject

添加到字典的正确方法是使用 updateValue,因为据我所知,您的字典中没有键"title",并且您正在将值附加到未知键我猜。

这应该会有所帮助:

    titleArray.append(postText)
    postDictionary.updateValue(titleArray as [AnyObject], forKey: "title")
    for (key,value) in postDictionary {
        print("(key) (value)") 
    }

最后,这应该打印:

标题 [帖子 1、帖子 2、帖子 3]

最新更新