Swift错误的指令错误购物清单

时间:2016-03-29 17:39:59

标签: ios arrays swift button exc-bad-instruction

我有一个问题,Xcode给我这个错误“EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码== 0 * 0)”而我正在尝试让我的按钮删除我的数组中的索引“shoppingList”。 请帮助我告诉我我做错了什么,以便我以后可以改进。

//
//  ViewController.swift
//  ShoppingList
//
//  Created by Petr Chrastek on 29/03/16.
//  Copyright © 2016 ACS. All rights reserved.
//
class ViewController: UIViewController {
    @IBOutlet weak var labelText: UILabel!
    @IBOutlet weak var label0: UILabel!
    @IBOutlet weak var label1: UILabel!
    @IBOutlet weak var label2: UILabel!
    @IBOutlet weak var label3: UILabel!
    var shoppingList = ["eggs", "milk", "cake", "sugar"]

    @IBAction func remove0(sender: UIButton) {
        shoppingList.removeAtIndex(0)
    }

    @IBAction func remove1(sender: UIButton) {
        shoppingList.removeAtIndex(1)
    }

    @IBAction func remove2(sender: UIButton) {
        shoppingList.removeAtIndex(2)
    }

    @IBAction func remove3(sender: UIButton) {
        shoppingList.removeAtIndex(3)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let str: String? = shoppingList[0]
        let str1: String? = shoppingList[1]
        let str2: String? = shoppingList[2]
        let str3: String? = shoppingList[3]
        let count = shoppingList.count
        labelText.text? = "you are missing \(count) items"
        if str != nil {
            label0.text? = "\(str)"
        } else {
            label0.text? = "empty"
        }
        if str1 != nil {
            label1.text? = "\(str1)"
        } else {
            label1.text? = "empty"
        }
        if str2 != nil {
            label2.text? = "\(str2)"
        } else {
            label2.text? = "empty"
        }
        if str3 != nil {
            label3.text? = "\(str3)"
        } else {
            label3.text? = "empty"
        }
        // Do any additional setup after loading the view, typically from a nib.
    }

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

1 个答案:

答案 0 :(得分:0)

从列表中删除第一项后,shoppingList只会包含3个项目,因此访问shoppingList[3]会崩溃(请记住3项只有0 ..< 2有效。

解决问题的最简单方法是使用以下模式,以便在使用之前检查计数以确保索引有效。

if shoppingList.count > 0 {
    label0.text = shoppingList[0]
} else {
    label0.text = "empty"
}

if shoppingList.count > 1 {
    label1.text = shopingList[1]
} else {
    label1.text = "empty"
}

我也进行了一些额外的更改,例如使用字符串插值将String变为同一String并非毫无意义,因为[String][n]将始终返回{{1} (永远不是String)没有必要处理String?

当你尝试:

时,你会遇到类似的问题(事实上,可能是你现在遇到的问题)
Optionals

第二次,因为3不再是有效索引,而是使用:

shoppingList.removeAtIndex(3)