WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Closures can now be marked @noescape

Available from Swift 1.2

Paul Hudson      @twostraws

Closures are reference types, which means Swift must quietly add memory management calls when they are passed into functions. To avoid adding unwanted work, you can now mark closure parameters with the @noescape keyword, which tells Swift the closure will be used before the function returns – it doesn't need to retain or release the closure.

As an example, this function checks whether a password that we have stored matches a password the user just entered, but it does this using a closure so that you can give it any encryption code you like. This closure is used immediately inside the function, so @noescape may be used as a performance optimization:

func checkPassword(encryption: @noescape (String) -> ()) -> Bool {
    if closure(enteredPassword) == storedPassword {
        return true
    } else {
        return false
    }
}

Note: This has changed in later versions of Swift – all closures are considered to be non-escaping by default.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 1.2…

Download all Swift 1.2 changes as a playground Link to Swift 1.2 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.