Skip to content

Instantly share code, notes, and snippets.

@SAllen0400
Last active March 8, 2017 22:59
Show Gist options
  • Save SAllen0400/5e574853dba95a4b87d35dc9d81f8664 to your computer and use it in GitHub Desktop.
Save SAllen0400/5e574853dba95a4b87d35dc9d81f8664 to your computer and use it in GitHub Desktop.
Sorting an array by an object property
// Swift 3
// Simple object example
class Phone {
let name: String
let serialNumber: Int
init(name: String, serialNumber: Int) {
self.name = name
self.serialNumber = serialNumber
}
}
// Create objects
let phoneOne = Phone(name: "Cell", serialNumber: 12345)
let phoneTwo = Phone(name: "Work", serialNumber: 24586)
let phoneThree = Phone(name: "Test Phone", serialNumber: 56893)
// Create array of Phones
var myPhones: [Phone] = [phoneOne, phoneTwo, phoneThree]
// Example 1: Sort array in-place by name in ASCENDING alphabetical order
// myPhones is now in this order: [phoneOne, phoneThree, phoneTwo]
myPhones.sort(by: { $0.name < $1.name })
// Example 2: Sort into a new array by serial number in DECENDING order
// newSortedArray is now in this order: [phoneThree, phoneTwo, phoneOne]
let newSortedArray = myPhones.sorted(by: { $0.serialNumber > $1.serialNumber})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment