Mastering Closure Behaviors in Swift: A Fun Dive | by Shobhakar Tiwari | December 2024
Interview iOS 𝗿𝗲𝘀𝗼𝘂𝗿𝗰𝗲𝘀 : Shobhakar Github
Closures in Swift can be sneaky: they behave differently depending on how you pass values. Let’s break down shutdown behavior with relevant examples and a pinch of humor.
Closures in Swift are like that friend who never forgets how much you loved pineapple pizza, even if your tastes change.
var favoriteFruit = "Apple"
viewModel.fruitFormatter = { _ in favoriteFruit }// Life happens, and you change your mind.
favoriteFruit = "Mango"
// But the closure still returns:
// "Apple" (It’s stuck in the past!)
For what? Closure captures favoriteFruit
at the time of its definition, not at the time of its call.
Closures can adapt based on the feedback you give them, like a barista brewing your coffee exactly how you want it.
viewModel.coffeeOrderFormatter = { order in
order ?? "Regular Coffee"
}// Calling the closure:
let result1 = viewModel.coffeeOrderFormatter?("Cappuccino") // "Cappuccino"
let result2 = viewModel.coffeeOrderFormatter?(nil)
For what? The closure processes the input dynamically and reverts to a default value if necessary.
Optional closures are like that friend who could help you move – if they are free and want to.
viewModel.moveHelper = nil
let moveStatus = viewModel.moveHelper?("Boxes") ?? "No Help Available"
For what? Closing only works if this is not the case nil
protecting your application from unwanted crashes.
During a Mentoring Session for Mock Interview on iOSone of my mentees struggled with shutting down behavior. We explored these tips, transforming the confusion of closures into clarity and cleaner code.
These techniques ensure that your code remains precise, modular, and secure. Give them a try and share if you’ve discovered any other clever closing tips!
Written by Shobhakar Tiwari | Lead iOS Engineer and Mentor
Before leaving: