【问题标题】:Fatal error: Index out of Range Swift 3.1致命错误:索引超出范围 Swift 3.1
【发布时间】:2017-05-22 05:02:31
【问题描述】:

所以发生的事情是,当程序试图访问我的 txt 文件的另外 2 行时,它正在爆炸,当我查看数组下的 xcode 时,它​​显示行由“\t”分隔,但它不会显示其他 2 行,这很令人抓狂……请在下面查看我的代码,感谢您的帮助。

var dictDoc = [String:String]()
var docArray = NSMutableArray()

override func viewDidLoad() {
    super.viewDidLoad()

    let path = Bundle.main.path(forResource: "docs", ofType: "txt")
    let fileMgr = FileManager.default
    if fileMgr.fileExists(atPath: path!){
        do{
            let fullText = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
            let readings = fullText.components(separatedBy: "\n") as [String]
            for i in 1..<readings.count {
                let docData = readings[i].components(separatedBy: "\t")
                dictDoc["Program"] = "\(docData[0])"
                dictDoc["Signature"] = "\(docData[1])"
                dictDoc["Extension"] = "\(docData[2])"
                docArray.add(dictDoc)
            }
        }catch let error as NSError{
            print("Error: \(error)")
        }
        self.title = "Word Processor Programs"
    }
    tableView.dataSource = self
    tableView.delegate = self
}

func numberOfSections(in tableView: UITableView) -> Int {    
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return docArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let doc = docArray[indexPath.row]
    cell.textLabel?.text = "\((doc as AnyObject).object(forKey: "Program")!)"
    cell.detailTextLabel?.text = "\((doc as AnyObject).object(forKey: "Signature")!)    \((doc as AnyObject).object(forKey: "Extension")!)"
    return cell
}

@IBAction func Closebtn(_ sender: UIButton) {
}

【问题讨论】:

  • 你能发布你试图分解成组件的文本吗?
  • Program Signautre Extension Word 2.0 DB A5 2D 00 DOC MS Pub subheader FD 37 7A 58 5A 00 PUB Acrobat 插件 4D 5A 90 00 03 00 00 00 API MS Pub 58 54 BDR WP dic 43 42 46 49 4C 45 CBD DeskMate Doc 0D 44 4F 43 DOC Perfect Office doc CF 11 E0 A1 B1 1A E1 00 DOC Word doc subheader EC A5 C1 00 DOC MS Off doc D0 CF 11 E0 A1 B1 1A E1 DOC|DOT|PPS|PPT
  • 它失去了格式,但这是一个示例
  • 您能否以应有的格式将文本添加到您的问题中。
  • 我刚刚尝试将字符串分配给操场上的一个变量,它在CBD DeskMate Doc 之前抛出了一个错误unprintable ASCII character found in source file。查看文件中使用的编码。我认为这一定是导致问题的原因。

标签: arrays swift swift3


【解决方案1】:

除了 Xcode 在复制文本时抱怨无法打印的 ASCII 字符之外,您的逻辑中还有一个细微的错误:注意最后的换行符。这意味着fullText.components(separatedBy: "\n") 为您提供了几乎您想要的东西,但带有一个额外的空字符串作为结果数组的最后一个元素。

可能的解决方案:

  • trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) 应用到fullText 以在拆分前去掉那个讨厌的换行符。
  • 过滤空字符串:let readings = fullText.components(separatedBy: "\n").filter { !$0.isEmpty }

哦,在我看来,API 和 MS Pub 之间的 \\ 应该是换行符:...API\n MS Pub...

更新

为了帮助您在将来跟踪这些错误并防止您的程序因fatal error: Index out of range 而崩溃, 例如,您可以添加 guard:

...
let docData = readings[i].components(separatedBy: "\t")
guard docData.count == 3 else {
    // Ignore, log message, throw error, whatever is appropriate in your use case.
    print("Unexpected format in \(readings[i])")
    continue
}
...

如果不以某种方式处理换行符,则会打印

'' 中的意外格式

我提到的\\ 也会显示:

“Acrobat 插件 4D 5A 90 00 03 00 00 00 API\MS Pub 58 54 BDR”中出现意外格式

【讨论】:

  • 抱歉回复晚了,你是救命恩人!!!!我不知道为什么要添加回车,我的意思是我已经尝试了一切来摆脱它,然后我看到了这一点,神奇的事情发生了!!!!
  • 不客气。作为一般说明,在解析您不确定其精确格式的数据时,广泛检查始终是一个好主意。即使你知道:每个人都会犯错误:)。我已经用一个例子更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多