UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

Forums > SwiftUI

Hello,

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 self.property

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

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.