Skip to content

Commit f92d9fe

Browse files
committed
Added Codable autoconformance
1 parent 7a0b191 commit f92d9fe

File tree

3 files changed

+79
-1
lines changed

3 files changed

+79
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ A few ways to have a lazily-initialized value in Swift 5.1. Note that, if you ar
1616

1717
# Automatic Conformance #
1818

19-
The built-in containers (`Lazy`, `ResettableLazy`, and `FunctionalLazy`) automatically conform to `Equatable` and `Hashable` when their values conform do too!
19+
The built-in containers (`Lazy`, `ResettableLazy`, and `FunctionalLazy`) automatically conform to `Equatable`, `Hashable`, `Encodable`, and `Decodable` when their values conform do too! This is a passthrough conformance, simply calling the functions of the wrapped value.
2020

2121
Keep in mind, though, that in order to do this, the value is automatically initialized and accessed!
2222

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
//
2+
// LazyContainer + Equatable.swift
3+
//
4+
//
5+
// Created by Ky on 2022-06-03.
6+
//
7+
8+
import Foundation
9+
10+
11+
12+
// MARK: - Encodable
13+
14+
public extension LazyContainer where Self: Encodable, Value: Encodable {
15+
func encode(to encoder: Encoder) throws {
16+
try wrappedValue.encode(to: encoder)
17+
}
18+
}
19+
20+
21+
22+
extension Lazy: Encodable where Value: Encodable {}
23+
extension ResettableLazy: Encodable where Value: Encodable {}
24+
extension FunctionalLazy: Encodable where Value: Encodable {}
25+
26+
27+
28+
// MARK: - Decodable
29+
30+
public extension LazyContainer where Self: Decodable, Value: Decodable {
31+
init(from decoder: Decoder) throws {
32+
self = .preinitialized(try Value(from: decoder))
33+
}
34+
}
35+
36+
37+
38+
extension Lazy: Decodable where Value: Decodable {}
39+
extension ResettableLazy: Decodable where Value: Decodable {}
40+
extension FunctionalLazy: Decodable where Value: Decodable {}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//
2+
// LazyContainer + Hashable tests.swift
3+
//
4+
//
5+
// Created by S🌟System on 2022-06-03.
6+
//
7+
8+
import XCTest
9+
10+
import LazyContainers
11+
12+
13+
14+
final class LazyContainer_Codable_tests: XCTestCase {
15+
16+
func testHashableConformance() {
17+
18+
struct Test: Codable {
19+
20+
@Lazy(initializer: { 42 })
21+
var lazyInt
22+
23+
@FunctionalLazy(initializer: { CGFloat.pi })
24+
var lazyFloat
25+
26+
@ResettableLazy(initializer: { "foobar" })
27+
var lazyString
28+
}
29+
30+
31+
32+
let encoder = JSONEncoder()
33+
encoder.outputFormatting = .sortedKeys
34+
35+
XCTAssertEqual(String(data: try encoder.encode(Test()), encoding: .utf8),
36+
#"{"lazyFloat":3.1415926535897931,"lazyInt":42,"lazyString":"foobar"}"#)
37+
}
38+
}

0 commit comments

Comments
 (0)