Swift Codable

Swift4.0 Codable使用

摘自:

Swifter - Swift必备tips

Everything about Codable in Swift 4

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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//
// main.swift
// TestCodable
//
// Created by Adrift on 2017/11/13.
// Copyright © 2017年 Adrift. All rights reserved.
//

import Foundation


struct Obj: Codable {

struct MenuItem: Codable {
let value: String
let onClick: String

enum CodingKeys: String, CodingKey {
case value
case onClick = "onclick"
}
}

struct Popup: Codable {
let menuItem: [MenuItem]

enum CodingKeys: String, CodingKey {
case menuItem = "menuitem"
}
}

struct Menu: Codable {
let id: String
// let id: String = "hello.id" 通过设置默认值的方式,可以忽略属性赋值
let value: String
let popup: Popup
}

let menu: Menu
}

let str = """
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
}
"""

if let data = str.data(using: String.Encoding.utf8) {
do {
let obj = try JSONDecoder().decode(Obj.self, from: data)
print(obj.menu.id)
} catch {
print(error)
}
}

//{
// "size":{
// "width":150,
// "height":150
// },
// "title":"Apple"
//}
//转成
//{
// "title":"Apple",
// "width":150,
// "height":150
//}

struct Size: Codable {
var width: Double
var height: Double
}

struct Photo {
var title: String
var size: Size

enum CodingKeys: String, CodingKey {
case title = "name"
case width
case height
}
}

extension Photo: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title, forKey: .title)
try container.encode(size.width, forKey: .width)
try container.encode(size.height, forKey: .height)
}
}

extension Photo: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title)
let width = try values.decode(Double.self, forKey: .width)
let height = try values.decode(Double.self, forKey: .height)
size = Size(width: width, height: height)
}
}

–EOF–