Menu
Coddy logo textTech

Recap - Custom Sorting

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 41 of 57.

challenge icon

Challenge

Hard

A music library sorts and deduplicates songs with the standard protocols. Song has title, artist, year and rating (1-5). Make it Equatable and Hashable on title and artist ignoring case (the same song by the same artist), Comparable by rating from high to low, then year from new to old, then title alphabetically, and CustomStringConvertible as Title - Artist (2019) **** with one star per rating point.

Complete playlist(_:), which removes duplicates (keeping the first) with a Set, sorts with sorted() and returns the songs' descriptions, then duplicates removed: 1.

The supplied code reads songs as title,artist,year,rating lines and prints each returned line.

Your code goes in Song.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
let songs = input.map { line -> Song in
    let p = line.split(separator: ",").map(String.init)
    return Song(title: p[0], artist: p[1], year: Int(p[2])!, rating: Int(p[3])!)
}
for line in playlist(songs) { print(line) }

All lessons in Object Oriented Programming

Practice on your own: Swift playground