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

Handle generic completion handlers in mocked function #57

Open
alschmut opened this issue Aug 8, 2022 · 0 comments
Open

Handle generic completion handlers in mocked function #57

alschmut opened this issue Aug 8, 2022 · 0 comments

Comments

@alschmut
Copy link

alschmut commented Aug 8, 2022

The below mocked generic completion handler does not compile as the generic Value can not be found outside the function.

Current state:

protocol MyProtocol {
    func foo<Value: Codable>(completion: (Value) -> Void)
}

class MyProtocolMock: MyProtocol {

    var invokedFoo = false
    var invokedFooCount = 0
    var stubbedFooCompletionResult: (Value, Void)? // Value can not be found

    func foo<Value: Codable>(completion: (Value) -> Void) {
        invokedFoo = true
        invokedFooCount += 1
        if let result = stubbedFooCompletionResult {
            completion(result.0)
        }
    }
}

Proposed solution:

protocol MyProtocol {
    func foo<Value: Codable>(completion: (Value) -> Void)
}

class MyProtocolMock: MyProtocol {

    var invokedFoo = false
    var invokedFooCount = 0
    var stubbedFooCompletionResult: (Any, Void)? // Change Value to Any

    func foo<Value: Codable>(completion: (Value) -> Void) {
        invokedFoo = true
        invokedFooCount += 1
        if let result = stubbedFooCompletionResult {
            completion(result.0 as! Value) // Force cast as Value
        }
    }
}

Ideally the solution also covers more complex completion handlers, where the generic type is nested. E.x:

func foo<Value: Codable>(completion: (Result<Value, Never>) -> Void)
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