ArraySlice index out of range in Swift

不想你离开。 提交于 2019-12-02 07:15:52

问题


I have data in the following format

["DATA1-1","DATA1-2","DATA1-3","DATA1-4","","DATA2-1","DATA2-2","DATA2-3","DATA2-4","","DATA3-1","DATA3-2","DATA3-3","DATA3-4",""].

I need to perform specific operations within each component of the array. The components are separated by "". In other words, I first need to perform an operation on ["DATA1-1","DATA1-2","DATA1-3","DATA1-4"], then the same operation on ["DATA2-1","DATA2-2","DATA2-3","DATA2-4"], etc.

First, I slice the array into separate segments, then iterate through each segment:

func arraySliceFunction(airway: [String])
    {           
        // Slice the master array with all combinations of airways into separate arrays
        var airwaySlices = airway.split("")

        // Iterate through the slices of arrays
        for i in 0..<airwaySlices.count
        {
            let sliceComponent = airwaySlices[i]

            // Iterate through each slice
            for var y = 0; y < sliceComponent.count; y++
            {
                print("SLICES COMPONENT: \(sliceComponent[y])")
            }
        }
    }

And it crashes on this line

print("SLICES COMPONENT: \(sliceComponent[y])")

always during the second iteration with an error: "fatal error: ArraySlice index out of range".

Have no idea why...

Thank you in advance!


回答1:


Try like this:

func arraySliceFunction(array: [String]) {
    // Slice the master array with all combinations of airways into separate arrays
    // Iterate through the each subArray 
    for subArray in array.split("") {
        // Iterate through each item in subArray
        for item in subArray {
            print("SLICES COMPONENT: \(item)")
        }
    }
}



回答2:


The code now works with Swift 2.2



来源:https://stackoverflow.com/questions/33557914/arrayslice-index-out-of-range-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!