简体   繁体   中英

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. but when I try to subscript with arc4random_uniform the error message not show up. can anyone show me what it wrong?

Thread: 1 fatal error: Index out of range

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

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

this is my 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()
    }
  }
}

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]

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

imageList have 3 items, and lastest item at index 2, similar with labelList , modify code at two lines:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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