Write an Efficient Code with Closure

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

Photo by Clyde He on Unsplash

Function inside Function

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

Place the Right Code in 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)
@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)

Wrap Up

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