Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Shared<T> to return shared instance in provider method #30

Open
ishkawa opened this issue Nov 13, 2017 · 0 comments
Open

Add Shared<T> to return shared instance in provider method #30

ishkawa opened this issue Nov 13, 2017 · 0 comments

Comments

@ishkawa
Copy link
Owner

ishkawa commented Nov 13, 2017

Rough sketch:

final class Counter {
    var value = 0
}

protocol MyResolver: Resolver {
    // A MyResolver instance always returns the same instance of Counter. 
    func provideCounter() -> Shared<Counter>
}

// Generated code
extension MyResolver {
    func resolveCounter() -> Counter {
        final class Scope {
            // NOTE: WeakDictionary doesn't present in standard library.
            static var sharedInstances = [:] as WeakDictionary<MyResolver, Counter>
        }

        // Return shared instance associated with MyResolver instance if it presents.
        if let sharedInstance = Scope.sharedInstances[self] {
            return associatedObject
        }

        // If shared instance is not found, call provider method and save returned instance as a shared instance.
        let sharedInstance = provideCounter()
        Scope.sharedInstances[self] = sharedInstance
        return sharedInstance
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant