Skip to content

Commit 0e24cd7

Browse files
committed
Add initialized flag
1 parent 8a76d2c commit 0e24cd7

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Sources/InstanceWrapper.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public final class Lazy<Service>: InstanceWrapper {
1616
private let factory: () -> Any?
1717
private let graphIdentifier: GraphIdentifier?
1818
private weak var container: Container?
19+
private(set) var initialized: Bool = false
1920

2021
init?(inContainer container: Container, withInstanceFactory factory: (() -> Any?)?) {
2122
guard let factory = factory else { return nil }
@@ -24,7 +25,11 @@ public final class Lazy<Service>: InstanceWrapper {
2425
self.container = container
2526
}
2627

27-
private var _instance: Service?
28+
private var _instance: Service? {
29+
didSet {
30+
initialized = _instance != nil
31+
}
32+
}
2833

2934
/// Getter for the wrapped object.
3035
/// It will be resolved from the `Container` when first accessed, all other calls will return the same instance.

Tests/SwinjectTests/LazySpec.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,5 +104,18 @@ class LazySpec: QuickSpec {
104104
expect(employee?.instance.employer).notTo(beNil())
105105
}
106106
}
107+
describe("Initialized flag") {
108+
it("provides instance from container") {
109+
container.register(Animal.self) { _ in Dog() }
110+
let lazy = container.resolve(Lazy<Animal>.self)
111+
expect(lazy?.instance is Dog).to(beTrue())
112+
expect(lazy?.initialized).to(beTrue())
113+
}
114+
it("provides instance from container but not initialized") {
115+
container.register(Animal.self) { _ in Dog() }
116+
let lazy = container.resolve(Lazy<Animal>.self)
117+
expect(lazy?.initialized).to(beFalse())
118+
}
119+
}
107120
}
108121
}

0 commit comments

Comments
 (0)