索引超出范围数组下标

index out of range array subscript

我尝试学习 S.O.L.I.D 原理,但当我想为数组下标时遇到问题,它显示错误消息。但是当我尝试使用 arc4random_uniform 下标时,错误消息没有出现。谁能告诉我哪里出了问题?

Thread: 1 fatal error: Index out of range

这是我在项目 Class

中的代码
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

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()
    }
  }
}

数组中的索引从 0 开始,因此 3 元素数组的索引为 0、1 和 2,并且 count = 3 因此要使用 count 访问数组的最后一项,您需要做 [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]

...

请注意 arc4random_uniform(n) returns 介于 0 和 n-1 之间的值,因此 arc4random_uniform(imageList.count) 将完美运行

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]