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

How to write a closure that returns a value

Written by 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.

Test your Swift today

Think you know Swift? My book Swift Coding Challenges will put your Swift skills to the test – it's perfect for job interviews and more!

Click here to visit the Hacking with Swift store >>