简体   繁体   English

索引超出范围数组下标

[英]index out of range array subscript

I try to learn SOLID principle and i have a problem when I want to subscript an array, it show an error message.我尝试学习 SOLID 原理,但当我想为数组下标时遇到问题,它显示错误消息。 but when I try to subscript with arc4random_uniform the error message not show up.但是当我尝试使用 arc4random_uniform 下标时,错误消息没有出现。 can anyone show me what it wrong?谁能告诉我有什么问题吗?

Thread: 1 fatal error: Index out of range主题:1 致命错误:索引超出范围

this is my code in Item 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: "")
    }
  }
}

update question.更新问题。 this is another error in appDelegate while fixing the subscript这是修复下标时 appDelegate 中的另一个错误

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

this is my itemStore class这是我的 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()
    }
  }
}

Index in an array starts at 0 so a 3 element array has indexes 0,1 and 2 and count = 3 so to access the last item of an array using count you need to do [someArray.count -1]数组中的索引从 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]

...

Notice that arc4random_uniform(n) returns a value between 0 and n-1 so doing arc4random_uniform(imageList.count) for instance will work perfectly请注意, arc4random_uniform(n)返回一个介于 0 和n-1之间的值,因此执行arc4random_uniform(imageList.count)将完美地工作

imageList have 3 items, and lastest item at index 2, similar with labelList , modify code at two lines: 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM