Sorting an array based on the value of a property

Hi everybody! Newbie here, trying to figure this one out.

Let’s say I have a struct Foo with a couple of members, one of which is an array.

struct Foo {
let name: String
let numbers: [Float]

And the array bar contains two instances of this type:

bar.append(Foo(name: “One”, numbers: [5, 3, 1]))
bar.append(Foo(name: “Two”, numbers: [6, 4, 2]))

How can I sort the array bar based on the contents of numbers[0]? From what I can see, neither sort() nor sort(by:) has an easy way to do this. Am I just structuring my data in a very odd way, or should there be an accessible way to do this?

sort(by:) is probably the easiest right now, other than conforming Foo to Comparable.

sort { $0.numbers[0] < $1.numbers[0] }

There's also this pitch: Map Sorting

1 Like

Works like a charm, thank you!