To decode JSON in Swift, you can use the JSONDecoder
class provided by the Foundation framework.
First, define a struct or class that conforms to the Decodable
protocol, which is used to represent the structure of the JSON data you want to decode.
Next, create an instance of JSONDecoder
and use its decode
method to convert the JSON data into your custom model object.
Make sure to handle any errors that may occur during the decoding process by using a do-catch block or by using the try?
keyword to decode the JSON data safely.
Once you have successfully decoded the JSON data, you can use the resulting model object in your Swift code.
What is the JSON decoding complexity in Swift?
In Swift, the complexity of JSON decoding depends on the size of the JSON data being decoded and the number of nested objects within it. Generally, JSON decoding in Swift has a time complexity of O(n), where n is the number of elements in the JSON data. The speed of decoding can also be influenced by the complexity of the data structure being decoded and the efficiency of the decoding algorithm used.
How to decode JSON arrays in Swift?
In Swift, you can decode JSON arrays by using the JSONDecoder
class and setting up a struct that conforms to the Decodable
protocol. Here is an example of how to decode a JSON array in Swift:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
struct Item: Codable { let name: String let price: Double } let json = """ [ { "name": "Item 1", "price": 10.99 }, { "name": "Item 2", "price": 5.99 } ] """.data(using: .utf8)! do { let items = try JSONDecoder().decode([Item].self, from: json) for item in items { print("Name: \(item.name), Price: \(item.price)") } } catch { print("Error decoding JSON: \(error)") } |
In this example, we first define a Item
struct that conforms to the Codable
protocol. We then create a JSON array representing a list of items, and convert it to a Data
object. We use JSONDecoder
to decode the JSON array into an array of Item
objects, and then iterate over the items to print their names and prices.
What is the Codable protocol in Swift?
The Codable protocol in Swift is a type alias for the Encodable and Decodable protocols. It allows a type to be encoded to and decoded from an external representation, such as JSON or plist. By conforming to the Codable protocol, a type can be easily serialized and deserialized without having to write custom encoding and decoding logic.