What the "in" keyword in Swift Closures means

codingfriend1

Gabriel Reimers

Posted on July 11, 2022

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
💖 💪 🙅 🚩
codingfriend1
Gabriel Reimers

Posted on July 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related