Member-only story

Using callback closure(block) passing data back in iOS

Mr.Javed Multani
2 min readOct 3, 2020

--

This topic is a classical issue in iOS development, and its solution is various as other example already shown. In this example I’ll show another daily common use one: passing data using closure by adapting delegate pattern example on this page into callback closure!

one thing this method is superior to delegate pattern is instead of split the setting up code in two different place( look at delegate example on this page, prepareForSegue ,userDidEnterInformation ) rather gathering them together( only in prepareForSegue, I’ll show it )

Start from Second View Controller

we must figure out how to use callback, then can we write it, this is why we start from second view controller since it’s where we use callback: when we got the new text input, we call our callback, using callback’s parameter as a medium to passing data back to first ViewController, notice that I said using callback’s parameter, this is very important, novices(as I was) always overlook this and don’t know where to start to write callback closure properly

so in this case, we know that our callback only take one parameter: text and its type is String, let’s declare it and make it property since we need populate from our first view controller

I just comment all the delegate part and keep it for comparing

class SecondViewController: UIViewController {
//weak var delegate: DataEnteredDelegate? = nilvar callback: ((String?)->())…

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer

No responses yet