回答編集履歴

2

さらに書き換え

2018/08/17 15:30

投稿

MasakiHori
MasakiHori

スコア3384

test CHANGED
@@ -10,21 +10,15 @@
10
10
 
11
11
 
12
12
 
13
- let key: String
14
-
15
-
16
-
17
- public var stringValue: String {
13
+ let stringValue: String
18
-
19
- return key
20
-
21
- }
22
14
 
23
15
 
24
16
 
25
17
  public var intValue: Int? {
26
18
 
19
+
20
+
27
- return Int(key)
21
+ return Int(stringValue)
28
22
 
29
23
  }
30
24
 
@@ -32,13 +26,17 @@
32
26
 
33
27
  public init?(stringValue: String) {
34
28
 
29
+
30
+
35
- key = stringValue
31
+ self.stringValue = stringValue
36
32
 
37
33
  }
38
34
 
39
35
  public init?(intValue: Int) {
40
36
 
37
+
38
+
41
- key = "(intValue)"
39
+ self.stringValue = "(intValue)"
42
40
 
43
41
  }
44
42
 
@@ -84,7 +82,7 @@
84
82
 
85
83
 
86
84
 
87
- key = codingKey.key
85
+ key = codingKey.stringValue
88
86
 
89
87
  value = try contener.decode(String.self, forKey: codingKey)
90
88
 

1

書き換え

2018/08/17 15:30

投稿

MasakiHori
MasakiHori

スコア3384

test CHANGED
@@ -1,14 +1,22 @@
1
- エラーは全部無視してます。
1
+ ~~エラーは全部無視してます。~~
2
+
3
+ エラー処理込みで書き換えました
2
4
 
3
5
 
4
6
 
5
7
  ```swift
6
8
 
7
- extension String: CodingKey {
9
+ struct InnerCodingKey: CodingKey {
10
+
11
+
12
+
13
+ let key: String
14
+
15
+
8
16
 
9
17
  public var stringValue: String {
10
18
 
11
- return self
19
+ return key
12
20
 
13
21
  }
14
22
 
@@ -16,7 +24,7 @@
16
24
 
17
25
  public var intValue: Int? {
18
26
 
19
- return Int(self)
27
+ return Int(key)
20
28
 
21
29
  }
22
30
 
@@ -24,15 +32,25 @@
24
32
 
25
33
  public init?(stringValue: String) {
26
34
 
27
- self = stringValue
35
+ key = stringValue
28
36
 
29
37
  }
30
38
 
31
39
  public init?(intValue: Int) {
32
40
 
33
- self = "(intValue)"
41
+ key = "(intValue)"
34
42
 
35
43
  }
44
+
45
+ }
46
+
47
+
48
+
49
+ enum InnerError: Error {
50
+
51
+
52
+
53
+ case hasNoKey
36
54
 
37
55
  }
38
56
 
@@ -48,51 +66,27 @@
48
66
 
49
67
 
50
68
 
51
- init(from decoder: Decoder) {
69
+ init(from decoder: Decoder) throws {
52
70
 
53
71
 
54
72
 
55
- guard let contener = try? decoder.container(keyedBy: String.self) else {
73
+ let contener = try decoder.container(keyedBy: InnerCodingKey.self)
74
+
75
+
76
+
77
+ guard let codingKey = contener.allKeys.first else {
56
78
 
57
79
 
58
80
 
59
- key = ""
60
-
61
- value = ""
81
+ throw InnerError.hasNoKey
62
-
63
- return
64
82
 
65
83
  }
66
84
 
67
85
 
68
86
 
69
- guard let aKey = contener.allKeys.first else {
87
+ key = codingKey.key
70
88
 
71
-
72
-
73
- key = ""
74
-
75
- value = ""
76
-
77
- return
78
-
79
- }
80
-
81
- key = aKey
82
-
83
-
84
-
85
- guard let aValue = try? contener.decode(String.self, forKey: key) else {
89
+ value = try contener.decode(String.self, forKey: codingKey)
86
-
87
-
88
-
89
- value = ""
90
-
91
- return
92
-
93
- }
94
-
95
- value = aValue
96
90
 
97
91
  }
98
92