Skip to content

Commit f79d510

Browse files
committed
TimeZone : Codable implemented
1 parent c55741b commit f79d510

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Foundation/TimeZone.swift

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,3 +280,26 @@ extension TimeZone {
280280
return result!
281281
}
282282
}
283+
284+
extension TimeZone : Codable {
285+
private enum CodingKeys : Int, CodingKey {
286+
case identifier
287+
}
288+
289+
public init(from decoder: Decoder) throws {
290+
let container = try decoder.container(keyedBy: CodingKeys.self)
291+
let identifier = try container.decode(String.self, forKey: .identifier)
292+
293+
guard let timeZone = TimeZone(identifier: identifier) else {
294+
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
295+
debugDescription: "Invalid TimeZone identifier."))
296+
}
297+
298+
self = timeZone
299+
}
300+
301+
public func encode(to encoder: Encoder) throws {
302+
var container = encoder.container(keyedBy: CodingKeys.self)
303+
try container.encode(self.identifier, forKey: .identifier)
304+
}
305+
}

TestFoundation/TestCodable.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,18 @@ class TestCodable : XCTestCase {
305305
}
306306
}
307307

308+
// MARK: - TimeZone
309+
lazy var timeZoneValues: [TimeZone] = [
310+
TimeZone(identifier: "America/Los_Angeles")!,
311+
TimeZone(identifier: "UTC")!,
312+
TimeZone.current
313+
]
314+
315+
func test_TimeZone_JSON() {
316+
for timeZone in timeZoneValues {
317+
expectRoundTripEqualityThroughJSON(for: timeZone)
318+
}
319+
}
308320
}
309321

310322
extension TestCodable {
@@ -323,6 +335,7 @@ extension TestCodable {
323335
("test_CGSize_JSON", test_CGSize_JSON),
324336
("test_CGRect_JSON", test_CGRect_JSON),
325337
("test_CharacterSet_JSON", test_CharacterSet_JSON),
338+
("test_TimeZone_JSON", test_TimeZone_JSON),
326339
]
327340
}
328341
}

0 commit comments

Comments
 (0)