Mobile Development
Swift
Subjective
Oct 04, 2025
What are closures in Swift and how are they used?
Detailed Explanation
Closures are self-contained blocks of functionality that can be passed around and used in code.\n\n• **Closure Syntax:**\n\n{ (parameters) -> ReturnType in\n statements\n}\n\n\n• **Common Uses:**\n• Higher-order functions (map, filter, reduce)\n• Completion handlers\n• Event handling\n• Asynchronous operations\n\n• **Examples:**\n\n// Basic closure\nlet greeting = { (name: String) -> String in\n return "Hello, \(name)!"\n}\n\n// Array operations\nlet numbers = [1, 2, 3, 4, 5]\nlet doubled = numbers.map { $0 * 2 }\nlet evens = numbers.filter { $0 % 2 == 0 }\nlet sum = numbers.reduce(0, +)\n\n// Trailing closure syntax\nUIView.animate(withDuration: 0.3) {\n view.alpha = 0.5\n}\n\n\n• **Capturing Values:**\n• Closures can capture and store references\n• Automatic memory management with ARC\n• Use weak/unowned to prevent retain cycles\n\n• **Escaping Closures:**\n• @escaping for closures that outlive function\n• Common in asynchronous operations
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts