You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift字典索引越界错误:日期匹配文本功能问题排查

解决Swift读取TXT文件分割时的Index out of range错误

问题原因

你的代码在分割每行时直接访问components[0]和components[1],但以下情况会触发数组越界:

  • TXT文件末尾存在空行(换行符分割出空字符串)
  • 某行未遵循「日期 : 文本内容」格式,缺少「 : 」分隔符
  • 行首/行尾的多余空格导致分割结果不符合预期

修复方案

  1. 过滤无效行:跳过空行,确保每行包含分隔符后再处理
  2. 安全访问数组元素:分割后先检查数组长度,避免直接索引越界
  3. 替换强制解包:用do-catch处理文件读取异常,避免崩溃
  4. 优化日期格式化:给DateFormatter设置固定locale,避免区域设置影响日期格式

修改后的代码

import Foundation

class NameDaysModel {

    private var dataArray: [String] = []

    func loadDictionary() -> [String: String] {
        var dictionary = [String: String]()
        let pathToFile = Bundle.main.path(forResource: "NameDays", ofType: "txt")

        guard let path = pathToFile else {
            print("无法找到NameDays.txt文件")
            return dictionary
        }

        do {
            let countriesString = try String(contentsOfFile: path, encoding: .utf8)
            dataArray = countriesString.components(separatedBy: "\n")
            
            for line in dataArray {
                let trimmedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
                // 跳过空行
                guard !trimmedLine.isEmpty else { continue }
                
                let components = trimmedLine.components(separatedBy: " : ")
                // 确保分割后至少有两个元素
                guard components.count >= 2 else {
                    print("无效行格式:\(line)")
                    continue
                }
                let dateKey = components[0].trimmingCharacters(in: .whitespaces)
                let contentValue = components[1].trimmingCharacters(in: .whitespaces)
                dictionary[dateKey] = contentValue
            }
        } catch {
            print("读取文件失败:\(error.localizedDescription)")
        }
        
        return dictionary
    }
   
    private func getDate() -> String {
        let date = Date()
        let dateFormatter = DateFormatter()
        // 设置固定locale避免区域影响日期格式
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "dd.MM.yyyy"
        return dateFormatter.string(from: date)
    }

    func getNameDay() -> String {
        let date = getDate()
        let nameDays = loadDictionary()
        return nameDays[date] ?? ""
    }
}

额外检查建议

  • 打开NameDays.txt文件,检查末尾是否有多余换行,或存在格式错误的行
  • 可以给TXT文件每行的日期和内容前后去掉多余空格,避免分割后出现空键值

内容的提问来源于stack exchange,提问作者Gucci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:15:40