Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Error: Cannot convert value of type 'Int' to expected argument type 'Double?'

import UIKit

fileprivate let reuseIdentifier = "vendingItem" fileprivate let screenWidth = UIScreen.main.bounds.width

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var balanceLabel: UILabel!
@IBOutlet weak var quantityLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var quantityStepper: UIStepper!

let vendingMachine: VendingMachine
var currentSelection: VendingSelection?

required init?(coder aDecoder: NSCoder) {
    do {
        let dictionary = try PlistConverter.dictionary(fromFile: "VendingInventory", ofType: "plist")
        let inventory = try InventoryUnarchiver.vendingInventory(fromDictionary: dictionary)
        self.vendingMachine = FoodVendingMachine(inventory: inventory)
    } catch let error {
        fatalError("\(error)")
    }

    super.init(coder: aDecoder)

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setupCollectionViewCells()

    updateDisplayWith(balance: vendingMachine.amountDeposited, totalPrice: 0, itemPrice: 0, itemQuantity: 1)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Setup

func setupCollectionViewCells() {
    let layout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)

    let padding: CGFloat = 10
    let itemWidth = screenWidth/3 - padding
    let itemHeight = screenWidth/3 - padding

    layout.itemSize = CGSize(width: itemWidth, height: itemHeight)
    layout.minimumLineSpacing = 10
    layout.minimumInteritemSpacing = 10

    collectionView.collectionViewLayout = layout
}

//MARK: - Vending Machine

@IBAction func purchase() {
    if let currentSelection = currentSelection {
        do {
            try vendingMachine.vend(selection: currentSelection, quantity: Int(quantityStepper.value))
            updateDisplayWith(balance: vendingMachine.amountDeposited, totalPrice: 0.0, itemPrice: 0, itemQuantity: 1)
        } catch VendingMachineError.outOfStock {
            showAlertWith(title: "Out of stock", message: "This item is unavailable. Please make another selection")
        } catch VendingMachineError.invalidSelection {
            showAlertWith(title: "Invalid selection", message: "Please make another selection")
        } catch VendingMachineError.insufficientFunds(let required) {
            let message = "You need ₹\(required) to complete the transaction"
        } catch let error {
            fatalError("\(error)")
        }

        if let indexPath = collectionView.indexPathsForSelectedItems?.first {
            collectionView.deselectItem(at: indexPath, animated: true)
            updateCell(having: indexPath, selected: false)
        }

    } else {
        // FIXME: Alert user no selection
    }
}

func updateDisplayWith(balance: Double? = nil, totalPrice: Double? = nil, itemPrice: Double? = nil, itemQuantity: Double? = nil) {

    if let balanceValue = balance {
        balanceLabel.text = "₹\(balanceValue)"
    }

    if let totalValue = totalPrice {
        totalLabel.text = "₹\(totalValue)"
    }

    if let priceValue = itemPrice {
         priceLabel.text = "₹\(priceValue)"
    }

    if let quantityValue = itemQuantity {
        quantityLabel.text = "\(quantityValue)"
    }
}

func updateTotalPrice(for item: VendingItem) {
    let totalPrice = item.price * quantityStepper.value
    updateDisplayWith(totalPrice: totalPrice)
}

@IBAction func updateValue(_ sender: UIStepper) {
    let quantity = Int(quantityStepper.value)
    updateDisplayWith(itemQuantity: quantity)

    if let currentSelection = currentSelection, let item = vendingMachine.item(forSelection: currentSelection) {
        updateTotalPrice(for: item)
    }
}

1 Answer

You are converting to Int here from Double and then trying to pass it into a parameter of type Double. Just don't convert it to Int.

@IBAction func updateValue(_ sender: UIStepper) {
        let quantity = Int(quantityStepper.value)
        updateDisplayWith(itemQuantity: quantity)

        if let currentSelection = currentSelection, let item = vendingMachine.item(forSelection: currentSelection) {
            updateTotalPrice(for: item)
        }
}

Change to:

@IBAction func updateValue(_ sender: UIStepper) {
        updateDisplayWith(itemQuantity: quantityStepper.value)

        if let currentSelection = currentSelection, let item = vendingMachine.item(forSelection: currentSelection) {
            updateTotalPrice(for: item)
        }
}

Thank u!!