Drux
Drux

Reputation: 12660

Cannot convert empty array of arrays to JSON with Swift 2

What is wrong with this piece of code (which was inspired by this example)? It currently prints JSON string "(<5b5d>, 4)" instead of the expected "[]".

var tags: [[String]] = []
// tags to be added later ...
do {
    let data = try NSJSONSerialization.dataWithJSONObject(tags, options: [])
    let json = String(data: data, encoding: NSUTF8StringEncoding)
    print("\(json)")
}
catch {
    fatalError("\(error)")
}

Upvotes: 1

Views: 747

Answers (1)

Martin R
Martin R

Reputation: 539765

Short answer: The creation of the JSON data is correct. The problem is in the conversion of the data to a string, what you want is the NSString method:

let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

which produces the expected [].

Slightly longer answer: Your code

let json = String(data: data, encoding: NSUTF8StringEncoding)

calls the String init method

/// Initialize `self` with the textual representation of `instance`.
/// ...
init<T>(_ instance: T)

and the result is the textual representation of the tuple (data: data, encoding: NSUTF8StringEncoding):

(<5b5d>, 4)

Actually you can call String() with arbitrary arguments

let s = String(foo: 1, bar: "baz")
print(s) // (1, "baz")

in Swift 2. This does not compile in Swift 1.2, so I am not sure if this is intended or not. I have posted a question in the Apple Developer Forums about that:

Upvotes: 4

Related Questions