Sort Swift 2 - Cannot call "sort" using a list of type arguments ...

I have a class, say Penguin

 class Penguin { var beakLength: Float } 

Trying to sort an Penguins array as follows:

 let penguins = [Penguin]() let sortedPenguins = penguins.sort { $0.beakLength < $1.beakLength } 

error message appears:

Cannot call 'sort' using a list of arguments of type '(@noescape (Penguin, Penguin) -> Bool)'

The expected list of arguments of type '(@noescape (Self.Generator.Element, Self.Generator.Element) -> Bool)'

What am I missing here?

+5
source share
4 answers

For those who have the same problem, it turns out that the above code example was not entirely correct. Which actually looks more like:

 var sortedPenguins = [Chimp]() let penguins = [Penguin]() sortedPenguins = penguins.sort { $0.beakLength < $1.beakLength } 

D'o!

+7
source

Note that in Swift 3 , the sort function performs in-place sorting and does not return a value ( mutating func sort() ). To create a sorted copy of the original array, you now use the sorted one ( func sorted() -> [Element] ).

+1
source
 class Penguin : CustomStringConvertible { var description: String { return beakLength.description } var beakLength: Float init(length: Float){ beakLength = length } } var penguins = [Penguin]() penguins.append(Penguin(length: 10)) penguins.append(Penguin(length: 20)) penguins.append(Penguin(length: 5)) print(penguins) print(penguins.sort { $0.beakLength < $1.beakLength }) 
0
source

Since Sort is deprecated in swift3, you can try this code for the maximum number of characters in the array.

 let Penguin = ["as","asc","you","bce","csi","aasi","aaas","this"] let maxLen = penguin.sorted{ $0.characters.count > $1.characters.count} print(maxLen) 

The result should be ["aasi", "aaas", "this", "asc", "you", "bce", "csi", "as"]

0
source

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


All Articles