Type inference fail

Before I begin I should note that I’ve become a fan of Swift’s trailing closure syntax and that’s what you’ll see here. There are a lot of ways to declare a closure, though, and I’m not particularly religious about my choice.

Also, this example applies to Swift 1.2 from Xcode 6.3 Beta 2. The language is still very much in flux.

When you’re using sort or sorted the compiler should know the argument types passed to the closure that does the comparison. The Swift documentation describes this:

The sorted function takes two arguments:

  • An array of values of a known type.
  • A closure that takes two arguments of the same type as the array’s contents, and returns a Bool value to say whether the first value should appear before or after the second value once the values are sorted. The sorting closure needs to return true if the first value should appear before the second value, and false otherwise.

This lets you write terse closures that don’t have to spell out the array type involved:

So you’d think it would work for slightly more complex data types (PhotoKit’s PHAsset in this case):

But I get this error:

Cannot find an overload for 'sorted' that accepts an argument of list of type '([PHAsset], (_,_) -> _)'

So instead I have to declare types for everything like I’m still at my C/C++ day job:

The same thing happens with sort.

It’s not a big deal, but I’ve come to enjoy Swift’s syntactic sugar and my slight OCD nature doesn’t like having this closure declared differently from the others in my code.