Sorting an Array by Two Fields in Swift

Assume we have the following Person model struct.

struct Person {
  let firstName: String
  let lastName: String
}

How could we sort an array of person [Person] in ascending order first by the firstName then by the lastName?

var personArray = [Person(firstName: Tim, lastName: Cook),
                   Person(firstName: Jerry, lastName: Cook),
                   Person(firstName: Ben, lastName: Anderson)]

personArray.sort {
  if $0.firstName != $1.firstName {
    return $0.firstName < $1.firstName
  } else {
    return $0.lastName < $1.lastName
  }
}

Posted

in

by

Tags:

Comments

Leave a comment