Junior — Middle
Is it possible to store functions-closures inside arrays in programming languages?
sobes.tech AI
Answer from AI
Yes, in programming languages that support functions as first-class objects (such as Swift, Objective-C, JavaScript), closure functions can be stored inside arrays or other collections.
In iOS (Swift), it looks like this:
let closures: [() -> Void] = [
{ print("First closure") },
{ print("Second closure") }
]
closures[0]() // Will output: First closure
This is convenient when you need to store a set of actions for later invocation, such as event handlers or deferred tasks. The main thing is to be careful with capturing variables inside closures to avoid memory leaks.