An object that decodes instances of a data type from JSON objects.

Declaration

class JSONDecoder

Discussion

The example below shows how to decode an instance of a simple GroceryProduct type from a JSON object. The type adopts Codable so that it's decodable using a JSONDecoder instance.

struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}

let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)

print(product.name) // Prints "Durian"

--

--

An object that encodes instances of a data type as JSON objects.

Declaration

class JSONEncoder

Discussion

The example below shows how to encode an instance of a simple GroceryProduct type from a JSON object. The type adopts Codable so that it's encodable as JSON using a JSONEncoder instance.

struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/* Prints:
{
"name" : "Pear",
"points" : 250,
"description" : "A ripe pear."
}
*/

--

--

There are three types of collections in swift

  1. Array
  2. Dictionary
  3. Set

Array

The array is an ordered collection type. we can access the element by the index

Dictionary

Dictionary is an unordered collection.

It’s a key-value data type. We can access the value by using the unique key.

Set

Set is also an unordered collection type. and it works on hashing

--

--