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! While you're at it, check out some resources Treehouse students have shared here.

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 Using the Vending Machine Updating the Price

get error of optional type VendingSelection?

here is part of my code, and error shows: Value of optional type 'VendingSelection?' not unwrapped; did you mean to use '!' or '?'?

// MARK: - UICollectionViewDelegate

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    updateCell(having: indexPath, selected: true)

    currentSelection = vendingMachine.selection[indexPath.row]

    if let currntselection = currentSelection, let item = vendingMachine.irem(forSelection: currentSelection) {

        priceLabel.text = "$\(item.price)"
        totalLabel.text = "$\(item.price * Double(quantity))"
    }
}

my code looks like the same as tutor's. I don't know where I did wrong..

1 Answer

Ignazio Calo
PLUS
Ignazio Calo
Courses Plus Student 1,819 Points

look at your line:

if let currntselection = currentSelection, let item = vendingMachine.irem(forSelection: currentSelection) { }

which object are you using inside the vendingMachine.irem(forSelection: currentSelection) ?

There is a typo on the first variable definition, therefore you're still using the global optional currentSelection object.

I really suggest to use different names inside the if let <something> = <something>.

Gavin Hobbs
Gavin Hobbs
5,205 Points

Hey Ignazio Calo we would use different names for if let <something> = <something>; however, those are the names Pasan used. I totally understand your reasoning though.