Chapter 19, Silver Challenge Solution

I first created a Book struct to hold the title, author, and average review score.

// Silver challenge
struct Book {
    let title: String
    let author: String
    let averageReview: Double
}

I then created the BookCollection type as a struct with the TabularDataSource protocol’s required methods. I also made the BookCollection struct conform to the CustomStringConvertible protocol and implemented its required description property. Additionally, I included a mutating function for adding books to the collection, which is represented by an array of type Book.

struct BookCollection: TabularDataSource, CustomStringConvertible {
    var books = [Book]()
    
    var description: String {
        return "BookCollection"
    }
    
    var numberOfRows: Int {
        return books.count
    }
    
    var numberOfColumns: Int {
        return 3
    }
    
    func label(forColumn column: Int) -> String {
        switch column {
        case 0: return "Title"
        case 1: return "Author"
        case 2: return "Average Review"
        default: fatalError("Invalid column!")
        }
    }
    
    func itemFor(row: Int, column: Int) -> String {
        let book = books[row]
        switch column {
        case 0: return book.title
        case 1: return book.author
        case 2: return String(book.averageReview)
        default: fatalError("Invalid column!")
        }
    }
    
    mutating func add(_ book: Book) {
        books.append(book)
    }
}

I finished up with some code to test my new functionality.

var library = BookCollection()
library.add(Book(title: "IT",
                 author: "Stephen King",
                 averageReview: 4.5))
library.add(Book(title: "The Lord of the Rings Illustrated", 
                 author: "J. R. R. Tolkien",
                 averageReview: 5))
library.add(Book(title: "Swift Programming: The Big Nerd Ranch Guide",
                 author: "Mikey Ward",
                 averageReview: 4.6))
printTable(library)

The resulting printout:

Table: BookCollection
| Title | Author | Average Review |
|    IT | Stephen King |            4.5 |
| The Lord of the Rings Illustrated | J. R. R. Tolkien |            5.0 |
| Swift Programming: The Big Nerd Ranch Guide | Mikey Ward |            4.6 |