Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading