DEV Community

Gabriel Reimers
Gabriel Reimers

Posted on

4 2

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".

Sentry growth stunted Image

If you are wasting time trying to track down the cause of a crash, it’s time for a better solution. Get your crash rates to zero (or close to zero as possible) with less time and effort.

Try Sentry for more visibility into crashes, better workflow tools, and customizable alerts and reporting.

Switch Tools 🔁

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay