Search code examples
iosswifttemplatescompletionhandlerobject-type

Swift - CompletionHandler templated as parameter in function (UsingObjectMapper)


I'm trying to pass a completionHandler as a parameter in a function (no problem here). My problem is that I have multiple precise Types possible that I can recieve in my completionHandler function.

So I thought, "Let's use templates", and I tried.

This is the scheme I want to use: FuncA(completionHandler as MyType?) -> FuncB(..){completionHandler(Mappable?)} -> FuncC(sender: T?){performSegueWithIdentifier("segue", sender)}

Problem: Func A is printing me an error Func B seems to be ok Func C seems to be ok

Do you guy know how to do that, I'm not used to templates yet ?? Thanks for any help :)


Solution

  • I don't believe you can cast completionHandler like that in a method signature. You're going to need to do your typecasting inside the method body. e.g.

      typealias handler = () -> Array<AnyObject>
    
      funcA(handler)
    
      func funcA<T>(completion: T?) -> funcB {
    
        if let completion = completion as? handler {
          let array = completion()
          //do whatever you want here
        }
      }