ArraySlice index out of range in Swift

2019-03-01 12:24发布

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!

2条回答
家丑人穷心不美
2楼-- · 2019-03-01 13:10

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)")
        }
    }
}
查看更多
Emotional °昔
3楼-- · 2019-03-01 13:11

The code now works with Swift 2.2

查看更多
登录 后发表回答