索引超出范围数组下标

时间:2019-02-25 07:10:34

标签: arrays swift subscript

我尝试学习S.O.L.I.D原理,当我要对数组下标时遇到问题,它显示一条错误消息。但是当我尝试使用arc4random_uniform下标时,错误消息未显示。谁能告诉我这是怎么回事?

  

线程:1个致命错误:索引超出范围

这是我在商品类中的代码

class Item: NSObject {
var imageName: String
var label: String

init(imageName: String, label: String) {
    self.imageName = imageName
    self.label = label

    super.init()
}

convenience init(list: Bool = false) {
    if list {
        let imageList = ["milada-vigerova", "david-rodrigo", "quran"]
        let labelList = ["Fiqih", "Hadist", "Tafsir"]

        // The sortImage and sort label, the error show up
        let sortImageName = imageList[imageList.count]
        let sortLabel = labelList[labelList.count]

        self.init(imageName: sortImageName, label: sortLabel)
    } else {
        self.init(imageName: "", label: "")
    }
  }
}

更新问题。这是修复下标时appDelegate中的另一个错误

let itemStore = ItemStore()
    let homeController = window?.rootViewController as! HomeController
    homeController.itemStore = itemStore

这是我的itemStore类

class ItemStore {
var allItems = [Item]()

@discardableResult func createItem() -> Item {
    let newItem = Item(list: true)
    allItems.append(newItem)

    return newItem
}

init() {
    for _ in 0..<3 {
        createItem()
    }
  }
}

2 个答案:

答案 0 :(得分:1)

数组中的索引从0开始,因此3元素数组的索引为0,1和2,并且count = 3,因此要使用count访问数组的最后一项,您需要执行{ {1}}

[someArray.count -1]

请注意,if list { let imageList = ["milada-vigerova", "david-rodrigo", "quran"] let labelList = ["Fiqih", "Hadist", "Tafsir"] // The sortImage and sort label, the error show up let sortImageName = imageList[imageList.count - 1] let sortLabel = labelList[labelList.count - 1] ... 返回一个介于0到arc4random_uniform(n)之间的值,因此例如执行n-1将会完美地工作

答案 1 :(得分:1)

imageList 有3个项目,最后一个项目位于索引2,类似于 labelList ,在两行中修改代码:

// The sortImage and sort label, the error show up
let sortImageName = imageList[imageList.count - 1]
let sortLabel = labelList[labelList.count - 1]