iOS Swift Closures

iamVariable
2 min readJun 12, 2024

Closures can capture and store references to any constants and variables from the context in which they’re defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

In Simple, Closures are nothing but, you can create a function and assign it to a variable. And you can call that function using that variable, and even pass that function into other functions as parameters.

Lets start with an simple example,

let firstname = {
print("My Firstname is Gary")
}

// and you can call this closure like below
firstname()

You can also pass the params to it.

let firstname = { (fname: String) in 
print("My Firstname is \(fname)")
}

// and you can call this closure like below
firstname("Gary")

Here is how you return a value from closure

let firstname = { (fname: String) -> String in 
return ("My Firstname is \(fname)")
}

// and you can call this closure like below
print(firstname("Gary"))

Its not end yet, you can also pass this to a function as a parameter

func printMyFullName(firstname: String, lastName: @escaping () -> Void) {
print("printing my firstname \(firstname).")
lastName()
print("Yay!! Done!")
}

let printLastname = { (lastName: String) in
return {
print("My lastname is \(lastName)")
}
}

// Now we pass the closure to the printMyFullName function.
printMyFullName(firstname: "Gilbert", lastName: printLastname("ONG"))

--

--

iamVariable

Experienced Mobile Application developer and in full software development lifecycle, including analysis, design, development, deployment.