What is the autoclosure attribute? - free Swift example code and tips
The @autoclosure attribute can be applied to a closure parameter for a function, and automatically creates a closure from an expression you pass in. When you call a function that uses this attribute, the code you write isn't a closure, but it becomes a closure, which can be a bit confusing – even the official Swift reference guide warns that overusing autoclosures makes your code harder to understand. To help you understand how it works, here's a trivial example: That code creates a printTest() method, which accepts a closure and calls it. As you can see, the print("Hello") is inside a closure that gets called between "Before" and "After", so the final output is "Before", "Hello", "After". If we used @autoclosure instead, it would allow us to rewrite the printTest() call so that it doesn't need braces, like this: These two pieces of code produce identical results thanks to @autoclosure. In the second code example, the print("Hello") won't be executed immediately because it gets wrapped
Swift version: 5.10 Paul Hudson @twostraws May 28th 2019 The @autoclosure attribute can be applied to a closure parameter for a function, and automatically creates a closure from an expression you pass in. When you call a function that uses this attribute, the code you write isn't a closure, but it becomes a closure, which can be a bit confusing – even the official Swift reference guide warns that overusing autoclosures makes your code harder to understand. To help you understand how it works, here's a trivial example: func printTest1(_ result: () -> Void) { print("Before") result()…
saved by
related reading
- How to Take Screenshots of Views in SwiftUItnvmadhav.me
- Methods - The Rust Programming Languagedoc.rust-lang.org
- Closures - The Rust Programming Languagedoc.rust-lang.org
- What the fuck is a closure? ・ Dan’s JavaScript Glossarywhatthefuck.is
- Building a menu using List - a free SwiftUI by Example tutorialhackingwithswift.com
- Swift Macros: Understanding Freestanding & Attached Macros - QuickBird Studiosquickbirdstudios.com
- SwiftUI by Example - free quick start tutorials for Swift developershackingwithswift.com
- Swift: From Protocol to AssociatedType then Type Erasure | Welcome to Monstarlab’s Engineering Blogengineering.monstar-lab.com
- Macros - The Rust Programming Languageweb.mit.edu
- Good examples of Clojure macros usage which demonstrate advantages of the language over the mainstream? - Stack Overflowstackoverflow.com
- The match Control Flow Construct - The Rust Programming Languagedoc.rust-lang.org
- Control Flow - The Rust Programming Languagedoc.rust-lang.org