NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

Strategy to let Void closures return data (i.e. project 16/HotProspects)

Forums > SwiftUI


after having worked through the 100 days, I'm can't get my head around some aspects of closures.

I get the concept - but it kind of puts you in a "cul-de-sac" of functionality.

It feels like any Void closure (and by the looks of it, a lòt of the standard API's use Void closures) can only be invoked as an end-of-a-one-way-street of function calls. And the data created in that final/crucial step is stuck in there.

For example: take this system call :

open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void)

It's a system call, with a closure protocol beyond my control.

I want to do more than a print( ) of the fetched data, but :

  • I can't send any fetched data back, as the closure must return void
  • the variable Data is inaccessible, as it is declared/assigned inside dataTask( )
  • I can't write to variables in the function, as this goes outside the closure's scope

It looks like the only way to get persistent data out of the closure is via assignment to a self-property :

  1. create a class
  2. give the class a method calling dataTask( ) - which then calls a closure
  3. in the closure, assign the data to a

This feels like an overkill solution ...

Am I missing something ? Is there an easier, more elegant solution to get to data created in Void closures ?

Thank you ! Bert


Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.