Search code examples
iosswiftclosuresblockcompletionhandler

Does blocks also use call back functiality as the complition handler does? (Swift/IOS)


There are questions with the similar to this one, what I have learned is that, completion handler using call back function, blocks are just anonymous functions or closures

Example of block and completion handler

class func scheduledTimer(withTimeInterval interval: TimeInterval, 
                  repeats: Bool, 
                    block: @escaping (Timer) -> Void) -> Timer


func startUpdates(from start: Date, 
      withHandler handler: @escaping CMPedometerHandler)

Question1

I've noticed that another difference is the completion handler has the typealias for the type, Does this applies to all ios framework design?

typealias CMPedometerHandler = (CMPedometerData?, Error?) -> Void

Question2

Does blocks also use call back function? Blocks are also has the escaping keywords, which means the closure will be called after the outer function has been returned, this sounds very "call back" to me.

Question3

If the answer for question 2 is yes, then what's the reason to reinvent the wheels, why not just call them all blocks or completion handlers


Solution

  • You are talking about terms which actually mean the same thing. Therefore your 3 questions cannot be answered separately.

    Both completion handler and callback are synonyms for an (escaping) closure – which is the Swift name for a block.
    @escaping indicates that the closure is called later after the enclosing function returns.

    A typealias is just a convenience identifier to replace the more complex right side with a simpler left side. It's not directly related to closures.