Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

Closures are functions; functions are closures

Anywhere that you can pass a closure, whether inline or as a named variable, you can also pass a function defined with the more familiar func statement.

The follow function in the following code makes use of a declared function, audioWisdom, a declared closure, visualWisdom, and an inline closure:

func audioWisdom() { print("Hear no evil") } 
let visualWisdom = { print("See no evil") }

struct Acolyte
{
func follow(theWay: Subroutine)
{
theWay()
}
}

struct WiseOne
{
func impartKnowledge(acolyte: Acolyte)
{
acolyte.follow(theWay: audioWisdom)
acolyte.follow(theWay: visualWisdom)
acolyte.follow(theWay: { print("Speak no evil") })
}
}

The higher order follow function has been passed both a function and closures as its theWay parameter.

There are a few differences between a function defined with func and a closure defined with let. The closure cannot be recursive, for example. However, in the majority of cases, the choice between function and closure declaration is a matter of taste and style, guided by convention and the situation at hand. Defining a dozen simple string operations with let will look a lot more concise, and therefore easier to read, than a dozen function declarations.