-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathContents.swift
77 lines (70 loc) · 2.01 KB
/
Contents.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//: [Previous Topic](@previous)
//: # Playground for presenting Simple Nested Codable
import Foundation
//: ### Decoding From JSON string to Message Object which contain a from Person object
//:1. Create A simple json `Data` from `JSON` String
/*:
A Message JSON Object
```
{
"message": "Hi, How are you?",
"create": 1523895892938,
"from": {
"name" : "Ali",
"age":25,
"email":"[email protected]",
"address":"Iran, Tehran"
}
}
```
*/
let jsonData = """
{
"message": "Hi, How are you?",
"create": 1523895892938,
"from": {
"name" : "Ali",
"age":25,
"email":"[email protected]",
"address":"Iran, Tehran"
}
}
""".data(using: .utf8)!
//:2. Define a struct and called Message which adapt to `Codable` Protocol
struct Message : Codable {
let message : String
let create : TimeInterval
let from : Person
//:3. Define a nested struct and named Person which adapted to `Codable` Protocol
struct Person : Codable {
let name : String
let age : Int
let email : String
let address : String
}
}
//:4. defind jsonDecoder as JSONDecoder
let jsonDecoder = JSONDecoder()
do {
/*:
5. we use `-decode` method to decode `jsonData` into message object with `try` option
- first parameter is type of Object which want convert into such as `Int`, `String`,
or Declared `struct` or `class`. The example is `Int.self`
- second parameter is `jsonData' which we want convert from it into our definded type
*/
let message = try jsonDecoder.decode(Message.self,from:jsonData)
//:6. print Decoded `Message` Object
print("""
message = \(message.message)
create = \(message.create)
from = \(message.from)
\n
""")
} catch {
/*:
7. Handling Error
* error occured while decoding json to message swift struct
*/
print("Error on decoding \(error)")
}
//: [Next Topics](@next)