Michael Michael - 1 year ago 119
Swift Question

Displaying an Array of type Double on UILabel in Xcode

I am trying to make a basic shopping cart app where you can add an item to your cart, store the cost of the item in an array and then have the array displayed when you click "Receipt". However, every time I click "Receipt" on my app, the simulator crashes and displays

"Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)

beside my line of code that reads "allItems += item". If anyone has any ideas as to how I can my array of numbers displayed in a UILabel using a for in loop, please let me know. I will post source code below. Thanks in advance

class ViewController: UIViewController {

var priceOfApple = 1.75
var cart = [Double]()
var total = 0.00

@IBOutlet weak var appName: UILabel!
@IBOutlet weak var Balance: UILabel!
@IBOutlet weak var Instructions: UILabel!
@IBOutlet weak var redApple: UIButton!
@IBOutlet weak var appleInfo: UILabel!
@IBOutlet weak var addToCart: UIButton!
@IBOutlet weak var itemsPurchased: UILabel!

@IBAction func selectedApple(sender: AnyObject) {

Instructions.hidden = true
appleInfo.hidden = false
addToCart.hidden = false

@IBAction func purchaseApple(sender: AnyObject) {

total += priceOfApple
Balance.text = "Balance : \(total)"
Instructions.hidden = false
appleInfo.hidden = true
addToCart.hidden = true


@IBAction func viewReceipt(sender: AnyObject) {

redApple.hidden = true
Instructions.hidden = true
itemsPurchased.hidden = false

for item in cart {

var allItems = Double(itemsPurchased.text!)!
allItems += item
allItems = Double(itemsPurchased.text!)!

Answer Source

If I understand correctly, this is what you should do:

First, create a variable outside the for-loop, then inside the loop that variable will start storing every value in the array separated by " ". Once It is done, you can display its value in the Label.

  var itemsInCart = ""

    for{

        itemsInCart += String(items) + " "

    itemsPurchased.text = itemsInCart

I hope it helps!!!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download