Inferring Using Context

The sort function must take an array and a function with a specific signature. In the example we’ve been working with, the function must take two parameters that are Strings. You cannot use any other types in this case. You and I know this, and Swift does, too. You can shorten the closure syntax because you know that s1 and s2 are Strings. You can also shorten the closure because you know that the return type must be a Bool. Who the heck needs to write a return type when you already know it must be a Bool? Here is a shorter closure you can pass to the sort function:

sort(&names,{s1, s2 in s1 < s2})

Now you have a much shorter, easier closure.

Let’s review what’s happened so far: You first ...

Get Learning Swift™ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.