-1

我有一个问题,当我试图让我的按钮删除数组“shoppingList”中的索引时,Xcode 给了我这个错误“EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode==0*0)”。请帮助我并告诉我我做错了什么,以便我以后可以改进。

//
//  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.
    }
}
4

1 回答 1

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"
}

我还进行了一些额外的更改,例如使用字符串插值将 aString变成相同的String,因为[String][n]将始终返回 a String(从不 a String?),因此无需处理Optionals

当您尝试:

shoppingList.removeAtIndex(3)

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

if shoppingList.count > 3 {
    shoppingList.removeAtIndex(3)
}
于 2016-03-29T19:12:20.343 回答