how to parse data in swift

Swift provides different mechanisms to parse data, but one of the most commonly used approaches is to parse JSON data into Swift objects. Here is an example of how to parse JSON using the Codable protocol:

Assuming you have the following JSON data:

{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}
65 chars
6 lines

You can create a Swift struct to match the JSON structure:

main.swift
struct Person: Codable {
    let name: String
    let age: Int
    let email: String
}
87 chars
6 lines

Then, use the JSONDecoder class to parse the JSON data into a Person object:

main.swift
let json = """
{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try decoder.decode(Person.self, from: json)
print(person.name) // John
print(person.age) // 30
print(person.email) // john@example.com
281 chars
14 lines

You can also parse data from other formats, such as XML or property lists, using the appropriate parsers in Swift.

gistlibby LogSnag