Swift中的元组数组 [英] Array of tuples in Swift

查看:387
本文介绍了Swift中的元组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

func parseJSON3(inputData: NSData) -> NSArray {
    var tempDict: (id:Int, ccomments:Int, post_date:String, post_title:String, url:String) = (id: 0, ccomments: 0, post_date: "null", post_title: "null", url: "null")
    var resultArray: (id:Int, ccomments:Int, post_date:String, post_title:String, url:String)[] = []
    var error: NSError?
    var jsonDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
    var firstArray = jsonDictionary.objectForKey("locations") as NSArray
    for dict in firstArray {
        tempDict.id = dict.valueForKey("ID") as Int
        tempDict.ccomments = dict.valueForKey("ccomments") as Int
        tempDict.post_date = dict.valueForKey("post_date") as String
        tempDict.post_title = dict.valueForKey("post_title") as String
        tempDict.url = dict.valueForKey("url") as String
        resultArray.append(tempDict)
    }
    return resultArray
}

在行

resultArray.append(tempDict)

我有一个错误:

呼叫中参数'ccomments'缺少参数

为什么?请帮助....

Why? Help please....

推荐答案

它在我看来像 resultArray.append()将元组视为一个变量参数,并尝试扩展元组以匹配其自己的参数。它抱怨你的第二个参数,因为它只是期待一个。我没有看到 Array.append()记录在任何地方的这种行为,所以我想说它是Swift中的一个错误。

It looks to me like resultArray.append() is treating the tuple a little bit like a variadic parameter, and trying to expand the tuple to match its own arguments. It's complaining about your second parameter because it's only expecting one. I haven't seen this behavior for Array.append() documented anywhere, so I would say it's a bug in Swift.

使用附加运算符 + = 似乎没有这个问题:

Using the appending operator += doesn't seem to have that issue:

resultArray += tempDict

这篇关于Swift中的元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆