【问题标题】:ArraySlice index out of range in SwiftSwift中的ArraySlice索引超出范围
【发布时间】:2016-02-07 01:49:29
【问题描述】:

我有以下格式的数据

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

我需要在数组的每个组件中执行特定的操作。组件用“”分隔。也就是说,我首先需要对["DATA1-1","DATA1-2","DATA1-3","DATA1-4"]进行操作,然后对["DATA2-1"进行同样的操作, "DATA2-2","DATA2-3","DATA2-4"]等

首先,我将数组分割成单独的段,然后遍历每个段:

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])")
            }
        }
    }

它在这一行崩溃

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

总是在第二次迭代中出现错误:“fatal error: ArraySlice index out of range”。

不知道为什么...

提前谢谢你!

【问题讨论】:

  • 这个问题有什么问题?如果有人处罚我,请您至少提供一个解释吗?

标签: arrays swift slice


【解决方案1】:

代码现在适用于 Swift 2.2

【讨论】:

    【解决方案2】:

    试试这样:

    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)")
            }
        }
    }
    

    【讨论】:

    • 有效!虽然我不明白为什么我的代码不起作用。非常感谢您的帮助。
    • 显然,Swift 不喜欢直接使用 Ints 进行范围。在stackoverflow.com/questions/36251822/… 看到我的问题
    • @Dieblitzen 抱歉回复晚了,数组切片不一定从索引 0 开始。解决方案是在迭代其元素时使用 indices 属性
    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2016-11-10
    相关资源
    最近更新 更多