ios - 基本 while 循环中索引超出范围

标签 ios swift while-loop indexoutofrangeexception

我正在解析 HTML 并重新格式化图像以使其更好地适应。由于某种原因,当我有多个图像需要解析时,我会超出范围,而且我一生都无法弄清楚为什么。

当 imgArray.count >1 时,我将使用带有递增计数器的标准 while 循环进行循环。

在一个示例中,imgArray 计数为 3,i 为 3,但我的循环超出了范围,尽管我可以看到 multImgArray 中直至 multImgArray[2] 的适当值

如您所见,我在数组位置中减 1 以保持计数整数和数组位置同步

  if image {
    var imgArray = image.components(separatedBy: "style=")
    imgArray.removeFirst() //to remove unused portion of html

    var newImgArray = [String]()
    var multImgArray = [[String]]()

    if imgArray.isEmpty == false {
      if imgArray.count == 1 {
        newImgArray = imgArray[0].components(separatedBy: ">")
      } else {            
        var i = 0
        while i < imgArray.count {
          i+=1
          multImgArray.append(imgArray[i-1].components(separatedBy: ">"))
        }
      }

编辑:

原始 HTML 片段

<p style="width:1000pt">

循环之后,我应该将每个图像的原始片段放入数组中。但是循环超出了范围,就好像 Xcode 试图附加不存在的数组位置一样。

最终预期输出(替换此处未显示的步骤,但根据其他人的请求添加了澄清步骤):

<p style="max-width:\(max-width)pt"> //where max-width is defined elsewhere as self.view.frame.width - 50

最佳答案

如果您对空字符串有疑问 - 您可以在处理数组之前删除它们。例如,您可以使用一些扩展:

extension Array where Element == String {

    func filterEmpty() -> [String] {
        return filter({ !$0.isEmpty })
    }
}

然后这样使用它:

let imgArray = image.components(separatedBy: "style=").filterEmpty()

另外,你的循环有点困惑。你可以在没有循环的情况下做到这一点。例如:

let image = "style=A>style=B>Bstyle=C>C"
var imgArray = image.components(separatedBy: "style=").filterEmpty()
var newImgArray = [String]()
var multImgArray = [[String]]()
switch imgArray.count {
case 2...:
    multImgArray = imgArray.map({ $0.components(separatedBy: ">").filterEmpty() })
case 1:
    newImgArray = imgArray[0].components(separatedBy: ">").filterEmpty()
default:
    break
}

所以,它可能会解决循环问题。希望对您有帮助

附注或者甚至这样:

let image = "style=A>style=B>Bstyle=C>C"
let imgArray = image.nonEmptyComponents(separatedBy: "style=")
let newImgArray = imgArray.first?.nonEmptyComponents(separatedBy: ">") ?? []
let multImgArray = imgArray.map({ $0.nonEmptyComponents(separatedBy: ">") })

extension Array where Element == String {

    func filterEmpty() -> [String] {
        return filter({ !$0.isEmpty })
    }
}

extension String {

    func nonEmptyComponents(separatedBy string: String) -> [String] {
        return components(separatedBy: string).filterEmpty()
    }
}

关于ios - 基本 while 循环中索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125427/

相关文章:

python - "while"循环问题

java - while 循环中两个条件之间的差异

ios - 显示/隐藏 barButtonItem

ios - Objective-C 中选择器上的 EXC_BAD_ACCESS

ios - 如何在 Swift 中创建一个类数组

ios - 由于错误代码 -1,存档未成功,尽管我可以使用开发配置文件在我的设备中进行构建和安装

ios - 如何正确引用/检索在 AppData 中创建的临时文件以将文件上传到服务器?

使用 pygame-change 播放音频时,python 无法中断 while 循环

ios - 解包 View Controller 值时出现 fatal error

ios - 如何在 Playground 上编译 Storyboard