“致命错误:数组索引超出范围swift”

时间:2023-01-15 16:41:23

The code being:

代码:

class Singleton {

    class var sharedInstance:Singleton {
        struct Static {
            static var instance:Singleton? = nil
            static var token:dispatch_once_t = 0
        }
        dispatch_once(&Static.token)
            {
                Static.instance = Singleton ()
        }
        return Static.instance!
    }

    var prayerArray = Array<PrayerSound>()

}

and:

和:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        let prayer = PrayerSound(namazName: cellLabel, pathString: filePath!, checked: checked)
        sinleton.prayerArray[cellindex] = prayer

}

1 个解决方案

#1


1  

You are initialising prayerArray as an empty array with the line var prayerArray = Array<PrayerSound>(). Therefore it has no elements. You have to either initialise it to have a certain length, or append items to it. I think what you want is to do is to initialise it to have enough elements to accept your indices. Something like

您正在将prayerArray初始化为一个空数组,该行var prayerArray = array ()。因此它没有元素。您必须对它进行初始化,使其具有一定的长度,或者向其添加项目。我认为你想做的是初始化它,使它有足够的元素来接受你的索引。类似的

var prayerArray = Array<PrayerSound>(count:64, repeatedValue: somePrayer)

var prayerArray = Array (count:64, repeatedValue: somePrayer)

Alternatively, you can declare it as an array of optionals, and set them to nil:

您也可以将其声明为一组选项,并将其设置为nil:

var prayerArray = Array<PrayerSound?>(count:64, repeatedValue: nil)

var prayerArray =数组< PrayerSound吗?>(数:64,repeatedValue:nil)

#1


1  

You are initialising prayerArray as an empty array with the line var prayerArray = Array<PrayerSound>(). Therefore it has no elements. You have to either initialise it to have a certain length, or append items to it. I think what you want is to do is to initialise it to have enough elements to accept your indices. Something like

您正在将prayerArray初始化为一个空数组,该行var prayerArray = array ()。因此它没有元素。您必须对它进行初始化,使其具有一定的长度,或者向其添加项目。我认为你想做的是初始化它,使它有足够的元素来接受你的索引。类似的

var prayerArray = Array<PrayerSound>(count:64, repeatedValue: somePrayer)

var prayerArray = Array (count:64, repeatedValue: somePrayer)

Alternatively, you can declare it as an array of optionals, and set them to nil:

您也可以将其声明为一组选项,并将其设置为nil:

var prayerArray = Array<PrayerSound?>(count:64, repeatedValue: nil)

var prayerArray =数组< PrayerSound吗?>(数:64,repeatedValue:nil)