Swift `in` keyword meaning?
In a named function, we declare the parameters and return type in the func
declaration line.
func say(s:String)->() {
// body
}
In an anonymous function, there is no func
declaration line - it's anonymous! So we do it with an in
line at the start of the body instead.
{
(s:String)->() in
// body
}
(That is the full form of an anonymous function. But then Swift has a series of rules allowing the return type, the parameter types, and even the parameter names and the whole in
line to be omitted under certain circumstances.)
Closure expression syntax has the following general form:
The question of what purpose in
serves has been well-answered by other users here; in summary: in
is a keyword defined in the Swift closure syntax as a separator between the function type and the function body in a closure:
{ /parameters and type/
in
/function body/ }
But for those who might be wondering "but why specifically the keyword in
?", here's a bit of history shared by Joe Groff, Senior Swift Compiler Engineer at Apple, on the Swift forums:
It's my fault, sorry. In the early days of Swift, we had a closure syntax that was very similar to traditional Javascript:
func (arg: -> Type, arg: Type) -> Return { ... }
While this is nice and regular syntax, it is of course also very bulky and awkward if you're trying to support expressive functional APIs, such as map/filter on collections, or if you want libraries to be able to provide closure-based APIs that feel like extensions of the language.
Our earliest adopters at Apple complained about this, and mandated that we support Ruby-style trailing closure syntax. This is tricky to fit into a C-style syntax like Swift's, and we tried many different iterations, including literally Ruby's
{|args| }
syntax, but many of them suffered from ambiguities or simply distaste and revolt from our early adopters. We wanted something that still looked like other parts of the language, but which could be parsed unambiguously and could span the breadth of use cases from a fully explicit function signature to extremely compact.We had already taken
in
as a keyword, we couldn't use->
like Java does because it's already used to denote the return type, and we were concerned that using=>
like C# would be too visually confusing.in
madexs.map { x in f(x) }
look vaguely likefor x in xs { f(x) }
, and people hated it less than the alternatives.
*Formatting and emphasis mine. And thanks to Nikita Belov's post on the Swift forums for helping my own understanding.
*
The start of the closure’s body is introduced by the in keyword. This keyword indicates that the definition of the closure’s parameters and return type has finished, and the body of the closure is about to begin.
*
Source: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html