DEV Community

Gabriel Reimers
Gabriel Reimers

Posted on

What the "in" keyword in Swift Closures means

Ever since I started programming in Swift if found the in keyword for closures a bit weird. It doesn't make much sense to me.
For example:

names.sorted(by: { (s1: String, s2: String) -> Bool in 
    return s1 > s2 
} )
Enter fullscreen mode Exit fullscreen mode

Today I found this explanation by Joe Groff, one of the original Swift engineers:

https://forums.swift.org/t/history-why-does-closure-syntax-use-the-keyword-in/21885

TL/DR:
There is no real meaning in in. It was chosen for a lack of a better keyword.

I personally think about in as an abbreviation for input, because that at least makes sense when the return type is inferred like here:

names.sorted(by: { s1, s2 in return s1 > s2 } )
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
julius_peinelt_15b1e7f5df profile image
Julius Peinelt

I always a assumed that it’s influenced by the let-expressions in StandardML like

let
    val a = 1
    val b = 2
in 
    a + b
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
marionauta profile image
Mario Nachbaur • Edited

I've always assumed it means "these variables in this expression/block of code".