"Free" functions

While == and < are useful in their own right, the Swift library provides you with many “free” functions and methods for types that conform to Equatable and Comparable.

For any collection you define that contains a Comparable type, such as an Array, you have access to methods such as sort() that are part of the standard library:

let teamA = Record(wins: 14, losses: 11) let teamB = Record(wins: 23, losses: 8) let teamC = Record(wins: 23, losses: 9) var leagueRecords = [teamA, teamB, teamC]

leagueRecords.sort()

// {wins 14, losses 11}

// {wins 23, losses 9}

// {wins 23, losses 8}

Since you’ve given Record the ability to compare two values, the standard library has all the information it needs to sort each element in an array of Records!

As you can see, implementing Comparable and Equatable gives you quite an arsenal of tools:

leagueRecords.max() // {wins 23, losses 8}

leagueRecords.min() // {wins 23, losses 9} leagueRecords.starts(with: [teamA, teamC]) // true leagueRecords.contains(teamA) // true

results matching ""

    No results matching ""