To sort a list of people by name in Swift, you can use the sorted(by:)
method of the Array
class along with a custom comparison closure that compares the name
property of the Person
objects.
Here's an example code snippet:
main.swift427 chars22 lines
In this code, we define a Person
struct with a name
property and an age
property. We then create an array of Person
objects and use the sort()
method to sort the array by name. The sorting closure $0.name < $1.name
compares the name
properties of two Person
objects, and returns true
if the first person's name is less than the second person's name. Finally, we loop through the sorted array and print the name
property of each Person
object in the sorted order.
gistlibby LogSnag