NEW! Master Swift design patterns with my latest book! >>

How to write a closure that returns a value

Paul Hudson       @twostraws

Like regular functions, closures can accept values and return values of your choosing: just write them out at the start of your closure, followed by the word in.

For example, we could write a greeting closure that accepts the name of a person to greet and returns a string using that name:

let greeting = { (name: String) -> String in
    return "Hello, \(name)!"
}

You can now call that just like any other function, passing in someone’s name as its only parameter:

let message = greeting("Taylor")

Available from iOS 8.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Want to build macOS apps?

Hacking with macOS delivers 18 awesome projects that teach you macOS development in no time – take control of your desktop today!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>