Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of tuples in Swift

I have a function:

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
}

In line

resultArray.append(tempDict)

I have an error:

Missing argument for parameter 'ccomments' in call

Why? Help please....

like image 287
Alexey Nakhimov Avatar asked Jun 13 '14 17:06

Alexey Nakhimov


People also ask

What is the use of tuple in Swift?

A Tuple is a constant or variable that can accommodate a group of values that can be of different data types and compounded for a single value. In easy words, a tuple is a structure that can hold multiple values of distinct data types.

What is difference between tuple and array in Swift?

Both tuples and arrays allow us to hold several values in one variable, but tuples hold a fixed set of things that can't be changed, whereas variable arrays can have items added to them indefinitely.

Are tuples ordered in Swift?

In Swift a tuple can consist of multiple different types. Tuples are ordered and elements of tuples can also be named. So we can access elements of a tuple both by position and name, and we can deconstruct data into a tuple using the assignment operator.

What is difference between array and tuple?

Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly.


1 Answers

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
like image 115
Nate Cook Avatar answered Sep 29 '22 18:09

Nate Cook