inferring type from context type judgment
Because the ordered closure is passed as a parameter to the function, Swift can determine the type of the parameter and the type of the return value based on the second parameter of the sort function. The type of this parameter is (string, string), Bool, which means string, Both string and bool types do not need to be declared when the closure is defined. Because all types can be determined by the system. Therefore, the parentheses that return arrows and parameter names can be omitted:
Reversed = sort (names, {s1, S2 in return s1 > s2})
When a closure is passed to a function, it is always the default to determine the type of the parameter and the type of return value, so you rarely need to write a standard complete closure format yourself.
In any case, you can display the claim type as you wish. To avoid ambiguity, such a way is to actively encourage referrals. In the example of the sort function, the purpose of closures is very clear.
implicit Returns from Single-expression Closures ( implicit return of single-expression closures )
Single-expression closures can implicitly return the result of a single expression by ignoring the keyword return:
Reversed = sort (names, {s1, s2 in S1 > s2})
Here, the second parameter of the sort function type explicitly requires the closure to return a bool value, because the closure contains a single expression (S1 > S2), which returns a bool value, which ignores the return keyword.
shorthand Argument Names ( abbreviated parameter name )
In Swift, the system automatically provides an abbreviated parameter name for the inline closure, $0,$1,$2., etc., which can be used to refer to the value of the closure parameter.
If you use an abbreviated name in a closure expression, you can omit the closure parameter list, the value and type of the abbreviated name are inferred from the function type, and the INT keyword can be omitted.:
Reversed = sort (names, {$ > $})
Here, $0,$1 refers to the first and second parameters of the closure.
Operator Functions ( operation function )
The closure expression above actually has a shorter notation.
Swift's string type defines a specialized greater than action method (>) for a function with two string arguments, which returns a value of type bool, which just matches the second parameter requirement of the sort function, so you can simply pass a greater than action (>) , the system will determine what you need:
Reversed = sort (names, >)