In my code, I have a struct like the following:
struct Object {
var name: String
var count: Int
I am now creating an array of 10 Objects with random names and random counts.
Is there an easy way to
a) sort them alphabetically
b) sort them numerically in ascending order
Basically, there will be an array like so:
[Object1, Object2, Object3]
.
Every Object has a name
and count
attribute, and I want the objects in that list be sorted via these two attributes.
Solution in Swift2 (using this solution: StackOverflow):
Object.sort{
if $0.name != $1.name {
return $0.name < $1.name
}
else {
//suits are the same
return $0.count < $1.count
}
}
However, this has been renamed to sorted(by: )
in Swift3, and I don't quit get how to do that.
Narusan, maybe this will help you. Let's say you have an array with your struct objects called objArray, then you can order it by the code bellow:
If you want to sort alphabetically and then numerically, you can:
That produces:
I added
A10
to your array, because without it, a simple alphabetic sort would have been sufficient. But I'm assuming you wantedA10
afterA4
, in which case the numeric comparison will do the job for you.You changed the example to be a struct with two properties. In that case, you can do something like:
Or, more concisely:
Or
Note, rather than putting this logic in the closure, I'd actually make
Foo
conform toComparable
:This keeps the comparison logic nicely encapsulated within the
Foo
type, where it belongs.Then you can just do the following to sort in place:
Or, alternatively, you can return a new array if you don't want to sort the original one in place:
You can still use shorthand for
sorted
:While less readable, it more closely mimics the
sort
syntax.