Write an Efficient Code with Closure

Explore a new way to write your code with Closure to write better efficient code

Wendy Liga
4 min readMar 2, 2020

It’s no secret that the iPhone user is expecting high-quality apps they used on their iPhone. Especially since Apple has set a high bar in terms of the quality of apps on the iPhone. They create their hardware and software, and this is the recipe for success. They can write very efficient software because they know what and how this hardware behaves. That being said, as an iOS Software Engineer, it is our “nature’s call” to write great apps that run smoothly, and “Just Work” on iPhone.

One Big aspect of great apps on the iPhone is code that runs efficiently. So what and how code can classify as an efficient code? There’s no specific definition of it, but most of the time, this code can be identified by several things like no redundant process or unnecessary code, optimal memory management, optimizing access of data, etc. There’s a lot of it. And still, until this date, people even debate and find ways to improve code to better efficiency.

And now I want to describe several ways how you can utilize closure to improve your code efficiency

Photo by Clyde He on Unsplash

Function inside Function

When you write a function, and maybe you find your self write repetitive code inside a function, you can utilize

func animate() {
let animation: () -> Void = {
UIView.animate(withDuration: 0.3, animations: {
// animation here
})
}
if Thread.isMainThread {
animation()
} else {
DispatchQueue.main.async(execute: animation)
}
}

In this case, I want to make sure my animation code runs on the main thread. So instead of repeating, I will create a closure that acts as a function.

Place the Right Code in the Right Time

Imagine closure as a way to pass a block of code without executing it, and then you can utilize it to run later for the right time.

func filter(
_ data: [String],
onRecoverFromError recoverData: () -> [String]) -> [String]
) {
// 1
if error {
return recoverData()
}

// ...
// ...
// ...
}
// 2
var recoverData: () -> [String] {
return { data in
// you need to do expensive task
}
}
filter(users, onRecoverFromError: recoverData)

In this example, this function filter(data: onRecoverFromError:) asks the callers to provide some fallback data. This fallback data will return every item that meets specific rules. The fallback data will only be called when the operation ends in error. So then it does not make sense to calculate this fallback data when it’s not being used. So closure coming handy here.

The closure will defer the execution of its block. The block code inside closure will not be executed if no code was running it. This behavior is convenient to help reduce expensive tasks in a case like this.

Let’s imagine you have a very expensive task that will be used on some condition, instead of calculating it, spend resources to handle it, why not defer its execution until the right condition instead.

For real example you can look apple’s log api for swift implementation

@inlinable    
public func log(level: Logger.Level, _ message: @autoclosure () -> Logger.Message, metadata: @autoclosure () -> Logger.Metadata? = nil, file: String = #file, function: String = #function, line: UInt = #line)

Which using closure for passing message and metadata params at its function. This implementation choosen because of performance reason described above.

Wrap Up

There are lots of ways to improve efficiency on your code, from reducing unnecessary processes, removing repetitive code, or how to use memory efficiently. And closure can provide several ways to do it.

In the end, efficient code will always be a debate topic, and the way we improve our code gradually is how we can truly achieve that. Try to think about the impact on the code you write, how this will affect performance, how to place code at the right time, and things will go the way you want.

Thanks for your attention. Maybe you can check my other article about Model is more than Data Structure. Until then, I hope to see you in my next article.

--

--

Wendy Liga

Learning Driven Life • iOS Software Writer at Tokopedia • Exploring Swift and Anything that Sounds Fun • Open Source Enthusiast