Skip to content

Commit

Permalink
Streamline handling of optionals in registered
Browse files Browse the repository at this point in the history
  • Loading branch information
hmlongco committed Jun 10, 2022
1 parent b64e23d commit 82625e1
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 9 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Factory Changelog

### 1.0.3

* Streamline handling of optionals in registered

### 1.0.2

* Refactored common scope cache mechanism
Expand Down
5 changes: 2 additions & 3 deletions Sources/Factory/Factory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,10 @@ open class SharedContainer {
defer { lock.unlock() }
lock.lock()
if let registration = registrations[id] {
let result = registration()
if let optional = result as? T? {
if _isOptional(T.self), let optional = registration() as? T? {
return optional
}
return result as? T
return registration() as? T
}
return nil
}
Expand Down
22 changes: 16 additions & 6 deletions Tests/FactoryTests/FactoryRegistrationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,26 @@ final class FactoryRegistrationTests: XCTestCase {
let service1 = Container.myServiceType()
XCTAssertTrue(service1.text() == "MyService")

Container.Registrations.push()

Container.myServiceType.register(factory: { MockService() })
// add registrtion and test initial state
Container.myServiceType.register(factory: { MockServiceN(1) })
let service2 = Container.myServiceType()
XCTAssertTrue(service2.text() == "MockService")
XCTAssertTrue(service2.text() == "MockService1")

// push and test changed state
Container.Registrations.push()
Container.myServiceType.register(factory: { MockServiceN(2) })
let service3 = Container.myServiceType()
XCTAssertTrue(service3.text() == "MockService2")

// pop and ensure we're back to initial state
Container.Registrations.pop()
let service4 = Container.myServiceType()
XCTAssertTrue(service4.text() == "MockService1")

let service3 = Container.myServiceType()
XCTAssertTrue(service3.text() == "MyService")
// pop again (which does nothing) and test for initial state
Container.Registrations.pop()
let service5 = Container.myServiceType()
XCTAssertTrue(service5.text() == "MockService1")
}

func testReset() throws {
Expand Down
11 changes: 11 additions & 0 deletions Tests/FactoryTests/MockServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ class MockService: MyServiceType {
}
}

class MockServiceN: MyServiceType {
let id = UUID()
let n: Int
init(_ n: Int) {
self.n = n
}
func text() -> String {
"MockService\(n)"
}
}

struct ValueService: MyServiceType {
let id = UUID()
func text() -> String {
Expand Down

0 comments on commit 82625e1

Please sign in to comment.