-2

I'm using Xcode 8.2.1. If I look at the documentation for Array I find this declaration for the max method:

public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element?

The argument label is by and the argument name is areInIncreasingOrder. Since the label is specified explicitly I thought it has to be included in a call to the function but the following code works if I omit the label (i.e by).

Am I misunderstanding how argument labels are used when calling a method? Or, is my example code calling a different version of the max method?

Example code:

let names = ["Talyor", "Paul", "Adele"]

let longest = names.max { $1.characters.count > $0.characters.count }
print(longest!)  // "Taylor
RobertJoseph
  • 7,968
  • 12
  • 68
  • 113
  • 2
    And `names.max(by: { $1.characters.count > $0.characters.count })` does compile as expected. What you used is the "trailing closure syntax". – Martin R Feb 21 '17 at 15:25
  • 1
    See the [Trailing Closure](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID102) section of the "The Swift Programming Language" book. – rmaddy Feb 21 '17 at 15:26

1 Answers1

1

When the last parameter of a method is a closure, you can write it in curly braces after the method call and omit the name of the parameter.

See the Trailing Closure documentation.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
DrummerB
  • 39,814
  • 12
  • 105
  • 142