We've seen how JSON format works, however in order to send or receive this String
(or any other kind of data) through internet, it needs to be converted to an array of bytes which can be represented with the Swift's variable type Data
.
We can convert any type of variable to Data and vice versa. In the following example, you can see how we convert a String to Data, which we will later use when working with servers and databases.
let json: String = """
{ "name": "Pablo", "age": 24 }
"""
let jsonData = json.data(using: .utf8)
We can use three consecutive quotes to declare a String over multiple lines, and more importantly, what is useful for us in this example, to include quotes within it, otherwise we would need to escape them using
\"
instead.
Utf-8 is a commonly used format for converting characters, numbers, and symbols, as each language could handle it differently. While there are several options available, this is the one we will typically use.
Be the first to comment