Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Vending Machine App in Swift 2.0 Displaying Additional Views Recap

Charlie O'Shea
Charlie O'Shea
18,737 Points

Extension Attempt: Display Available Stock

I thought it'd be a useful exercise to try and extend the vending machine by adding a label which displays the current stock for an item when selected, and decrements it when purchased. I've made a working implementation of it which I call during purchase() and didSelectItemAtIndexPath.

But I'm fairly sure that I've overcomplicated my code for something that should be relatively simple and I have had to resort to a ! when changing types within the function which I'd like help in getting rid of. Is there a more elegant solution?

    func stockForCurrentSelection(selected: VendingSelection) -> String {

        if let item = vendingMachine.inventory[selected],
            let available: Double? = item.quantity {
            let availableInt = Int(available!)
            return String(availableInt)


        return "0"
@IBOutlet weak var availableLabel: UILabel!
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        updateCellBackgroundColor(indexPath, selected: true)
        currentSelection = vendingMachine.selection[indexPath.row]

        if let currentSelection = currentSelection {
            availableLabel.text = stockForCurrentSelection(currentSelection)