Swift Array.sort () will not accept closing in short format

I am having a strange problem with the Array.sort () function. He cannot accept an abbreviated closure. Xcode complains about the following message when using abbreviated closure: Cannot invoke 'sort' with an argument list of type '((_, _) -> _)' But it works with a longer form of the same closure.

 var names = ["Al", "Mike", "Clint", "Bob"] // This `sort()` function call fails: names.sort { $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending } // This `sort()` function call works: names.sort { (first: String, second: String) in return first.localizedCaseInsensitiveCompare(second) == .OrderedAscending } 

To make things redundant, if I first use a long closing form and then sort again using the shortened form, it works great!

 var names = ["Al", "Mike", "Clint", "Bob"] // Works fine, orders the array alphabetically names.sort { (first: String, second: String) in return first.localizedCaseInsensitiveCompare(second) == .OrderedAscending } // This shorthand version now works as well, reversing the order of the array names.sort { $0.localizedCaseInsensitiveCompare($1) == .OrderedDescending } 

So, the best scenario, I am doing something wrong and finding out something. In the worst case, this is just a silly mistake with Xcode or Swift.

Any ideas?

+6
source share
1 answer

as @Martin R pointed out, the root of the problem is that you are calling a method from NSString for the type Swift String.

it works great

 names.sort { $0 <= $1 } 
-1
source

Source: https://habr.com/ru/post/988679/


All Articles