Search code examples
jsonswiftparsing

String.data(using: .utf8): What is the effect of having the argument specified?


From an video-tutorial, which I'm currently using for learning:

let data = """
{
    "customers": [
        {
            "firstname": "John",
            /* ... */
        }
    ]
}
""".data(using: .utf8)

What does the .data-method? From what I read in the documentation, I would say it loads the data into a buffer.

But what's the argument with the label 'using'?

Can someone explain in a easy way what happens there?


Solution

  • This code is converting a String to Data, because presumably this will then get passed to a JSONDecoder to decode. Data represents

    A byte buffer in memory

    so a sequence of bytes. Note that String does not represent a sequence of bytes. It is a sequence of Characters. To convert Characters to bytes, you need an encoding. Different encodings can convert the same character to different byte sequences.

    .utf8 is one of the encodings. There are many more. JSON data should be transmitted in UTF-8, so that's why .utf8 is used here.