1

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

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

5 Comments

What a "bridge"! :) Thx.
Absolutely brilliant. Anyway, you only convert JSON data to a string for debugging.
And I haven't found any guarantee anywhere that the JSON data would be UTF-8 encoded.
@gnasher729: It's not a guarantee, but tools.ietf.org/html/rfc7159#section-8.1 states: "The default encoding is UTF-8, ...". – On the other hand, OP's original code now works as expected, because String has an init?(data: NSData, encoding: NSStringEncoding) method now.
@gnasher729: Also the documentation for dataWithJSONObject explicitly states: "The resulting data is encoded in UTF-8."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.