Skip to content

Question about using closure type constants in Dependency #65

Description

@kosukeohmura

When I define a class that conforms to Injectable and has a closure in its Dependency like below:

class SomeModel: Injectable {
    struct Dependency {
        let stringFactory: (Int) -> String
    }

    let stringFactory: (Int) -> String

    required init(dependency: Dependency) {
        self.stringFactory = dependency.stringFactory
    }
}

Then, I run dikitgen and I get error below. Closures in function parameter need @escaping.

    // Passing non-escaping parameter 'stringFactory' to function expecting an @escaping closure
    // Parameter 'stringFactory' is implicitly non-escaping
    func resolveSomeModel(stringFactory: (Int) -> String) -> SomeModel {
        return SomeModel(dependency: .init(stringFactory: stringFactory))
    }

I can avoid this error by creating factory container like below:

struct StringFactoryContainer {
    let factory:  (Int) -> String
}

And use like this:

class SomeModel: Injectable {
    struct Dependency {
        let stringFactoryContainer: StringFactoryContainer
    }

    let stringFactory: (Int) -> String

    required init(dependency: Dependency) {
        self.stringFactory = dependency.stringFactoryContainer.factory
    }
}

Does anyone know good way to use closure in Dependency?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions