How to write a method in Swift that accepts a closure


To write a method that accepts an anonymous closure is simple. It relies on using the accepts and returns syntax, written for example:

(String)->String

Once we understand this, a whole world of possibilities opens up. The start of which might be something like:

 func myClosureMethod (name:String, processor:(String)->String) {
        var newText = processor(name)
        println(newText)
    }

The thing to note here is the way in which we call the closure, by treating the name of the closure like it was a method using processor().

We'd then call the method in this way:

self.myClosureMethod("Peter Pan", processor: {textstring in "Hello " + textstring})

indicating a closure using the code braces, then assigning the parameter being sent to the closure a name – 'textstring' – and then manipulating it before the string is returned implicitly.

Don't worry too much about the in word, it simply separates the parameter name from the body of the closure.

Note

The term closure in Swift is treated in a more general way than found elsewhere:

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. Apple Developer Site

and this is something that I hope to explore in greater detail in a later post.



Endorse on Coderwall

Comments