Bronze Challenge Solution

Section:

class Section {
    var name: String
    var items: [Item]
    
    init(name: String, items: [Item]) {
        self.name = name
        self.items = items
    }
}

ItemsViewController:

class ItemsViewController: UITableViewController {
    
    var itemStore: ItemStore!
    var sections = [Section]()
    var expensiveSection = Section(name: "Over $50 Items", items: [Item]())
    var cheapSection = Section(name: "Other Items", items: [Item]())
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Get the height of the status bar
        let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height
        
        let insets = UIEdgeInsets(top: statusBarHeight, left: 0, bottom: 0, right: 0)
        tableView.contentInset = insets
        tableView.scrollIndicatorInsets = insets
        
        for item in itemStore.allItems {
            if item.valueInDollars > 50 {
                expensiveSection.items.append(item)
            } else {
                cheapSection.items.append(item)
            }
        }
        
        sections.append(expensiveSection)
        sections.append(cheapSection)
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return sections.count
    }
    
    override func tableView(tableView: UITableView,
                            numberOfRowsInSection section: Int) -> Int {
        return sections[section].items.count
    }
    
    override func tableView(tableView: UITableView,
                            titleForHeaderInSection section: Int) -> String? {
        return sections[section].name
    }
    
    override func tableView(tableView: UITableView,
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Get a new or recycled cell
        let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath)
        
        // Set the text on the cell with the description of the item
        // that is at the nth index of items, where n = row this cell
        let item = sections[indexPath.section].items[indexPath.row]
        
        cell.textLabel?.text = item.name
        cell.detailTextLabel?.text = "$\(item.valueInDollars)"
        
        return cell
    }
    
}
4 Likes

This is a thing of beauty. :slight_smile:

very nice, it works well. thanks

Thanks for the kind words!