Search code examples
arraysswiftsubscript

index out of range array subscript


I try to learn S.O.L.I.D 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()
    }
  }
}

Solution

  • 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]