如何更新位于Array的每个索引的Swift中的字典

时间:2014-11-24 11:37:17

标签: dictionary swift ios8 xcode6.1

此响应来自JSON格式的服务器 posts =

(
            {
        commentCount = 0;
        "country_id" = 225;
        "country_name" = "United States";
        dislikeCount = 2;
        disliked = 0;
        firstname = Test;
        imageHeight = 0;
        imagePath = "";
        imageWidth = 0;
        lastname = Test;
        likeCount = 2;
        liked = 0;
        postid = 126;
        posttime = "2014-11-10 12:26:43";
        shareCount = 0;
        statusUpdate = Hello;
        "upload_type" = text;
        userId = 13;
        userimage = "https://Test.com/1409976093.png";
        videoHeight = "";
        videoPath = "";
        videoThumbnail = "";
        videoWidth = "";
    },
            {
        commentCount = 0;
        "country_id" = 225;
        "country_name" = "United States";
        dislikeCount = 2;
        disliked = 0;
        firstname = Test;
        imageHeight = 0;
        imagePath = "";
        imageWidth = 0;
        lastname = Test;
        likeCount = 3;
        liked = 0;
        postid = 125;
        posttime = "2014-10-28 17:50:00";
        shareCount = 0;
        statusUpdate = "Happy%20chhata%20puja%20to%20you%20and%20your%20family%0Athanks%0ADr%20shah%20family";
        "upload_type" = text;
        userId = 78;
        userimage = "https://Test.com/1410142960.png";
        videoHeight = "";
        videoPath = "";
        videoThumbnail = "";
        videoWidth = "";
    }

现在我需要更新"喜欢"的价值从0到1本地,但我无法做到这一点。我把这个数组存储在我的数组中:

self.homePageDataArray.addObjectsFromArray(dictionary["posts"] as NSMutableArray)

我能够从每个索引中获取内容,并且能够在TableView中显示这个内容,但我想改变"喜欢"的状态。从0到1,用户将点击" Like Button"在我的应用程序中显然我会在服务器上更新这个,但我想在本地更新并行。 请让我知道如何实现。我尝试了很多,但每次都显示一些错误!对于实例,

var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary

我收到此错误

Type 'AnyObject' does not conform to protocol 'Hashable'

最终,我希望能够使用&#34; updateValue&#34;方法,以便我可以在我的数组中更新我的字典的值。

2 个答案:

答案 0 :(得分:1)

这应该适合你:

var tempDic = self.homePageDataArray[selectedRow] as Dictionary<String, AnyObject>

您的版本:

var tempDic:Dictionary<AnyObject,AnyObject> = self.homePageDataArray[selectedRow] as Dictionary

无效,因为AnyObject不符合HashableDictionary中对通用密钥类型的要求。


并回答你的other question

var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary

上面的陈述编译,因为Dictionary可以与它的Objective-C对应物联系起来; NSMutableDictionary。您生成的字典将为Dictionary<String, AnyObject>类型。您可能想知道类型String是如何被推断出来的。好吧,NSMutableDictionary使用NSString作为键,这种类型可以与它的Swift对应物联系起来,你猜对了; String

答案 1 :(得分:0)

我真的不知道为什么,,但以下解决方案为我工作

var tempDic = self.homePageDataArray[selectedRow] as NSMutableDictionary as Dictionary

如果有人能解释那么它也会帮助别人!