I'm having some problem in sorting an array of objects:
class Genome {
var id: Float?
var won: Float?
var lost: Float?
var drew: Float?
var fitness: Int = Int.random(in: 0...100)
init(id: Float, won: Float, lost: Float, drew: Float) {
self.id = id
self.won = won
self.lost = won
self.drew = drew
}
}
This is the object. I have an array of 50 "Genome" objects and I need to sort it using its fitness property.
I already tried this:
genomes.sorted({ $0.fitness > $1.fitness })
But it didn't work. How can I do that?
sorted
has a return value. You have to declare a new variable and in creasing order is <
let sortedGenomes = genomes.sorted{ $0.fitness < $1.fitness }
To sort genomes
in place use sort
genomes.sort{ $0.fitness < $1.fitness }
Side note: Don't declare properties as optional which are initialized with non-optional values.
Swift 3 & Swift 4 & Swift 5
This will sort your object array in ascending order.
let sortedGenomes = genomes.sorted(by: { $0.fitness < $1.fitness })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.