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

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

The above function retrieves the pedometer data from your iOS device. When I called the function the only argument I need passed to is the parameter from start.

Who actually initialized the parameter list of the completion handler closure? The startUpdates function I've called?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
SLN
  • 4,772
  • 2
  • 38
  • 79

1 Answers1

1

When I called the function the only argument I need to passed to is the parameter from start

That's not true.

You have to pass also the closure as second parameter. The closure itself is called by the startUpdates function after doing its work and passes two parameters back, an optional Data and an optional Error instance.

The functional programming is a very convenient way to be able to run arbitrary code (in the closure).

You can declare the closure separately

let result : CMPedometerHandler = { data, error in
    if let error = error { print(error); return }
    // do something with the data 

}

startUpdates(from: Date(), withHandler: result)

or inline

startUpdates(from: Date(), withHandler: { data, error in
    if let error = error { print(error); return }
    // do something with the data 

})

or with trailing closure syntax

startUpdates(from: Date()) { data, error in
    if let error = error { print(error); return }
    // do something with the data 

}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • ! ah I got it, I have to pass the closure as argument to the function, the closure is how I want to process the CMPedometerData ane Error later in the run time, but the the initialization of CMPedometerData ane Error will be done by the function. Its seems as if I passed a predicate to a it to guide how to process the data. – SLN Aug 25 '18 at 10:10
  • 1
    Yes, it's similar like passing a predicate – vadian Aug 25 '18 at 10:46