concept BooksManager in category ios

appears as: The BooksMager, BooksMager, BooksMager, BooksManager
iOS Development with Swift

This is an excerpt from Manning's book iOS Development with Swift.

Call your friendly librarian class the BooksManager. The BooksManager will lazily load an array of books that’s preloaded with sample data.

  • Create a BooksManager Swift file preconfigured with a computed property for returning the number of books (bookCount), a method returning a specific book (getBook), and a lazy property (the books array) that preloads with sample data.
    import Foundation
    class BooksManager {
       private lazy var books: [Book] = self.loadBooks()       1
       var bookCount: Int {return books.count}                 2
       func getBook(at index: Int) -> Book {                   3
           return books[index]                                 3
       }                                                       3
    
       private func loadBooks() -> [Book] {                    4
           return sampleBooks()                                4
       }                                                       4
       private func sampleBooks() -> [Book] {                  5
           let books = [                                       5
               Book(title: "Great Expectations",               5
                   author: "Charles Dickens",                  5
                   rating: 5,                                  5
                   isbn: "9780140817997",                      5
                   notes: "from Papa"),                        5
                   // Enter more sample books here             5
           ]                                                   5
           return books                                        6
       }
    }
    • 1 Lazy load books array
    • 2 Calculates number of books
    • 3 Returns a book
    • 4 Loads books
    • 5 Creates sample books array
    • 6 Returns array
  • Believe it or not, you’re only going to have to make changes to the BooksManager class to keep the data nicely sorted.

    This method now needs to let the BooksManager know that you want the sort order changed, and to update the table.

  • Add the SortOrder enumeration to the BooksManager.swift file, but before the BooksManager class.
  • Add a sortOrder property to the BooksManager class that defaults to .title initially.
    var sortOrder = SortOrder.title