Swift字典索引越界错误:日期匹配文本功能问题排查
解决Swift读取TXT文件分割时的Index out of range错误
问题原因
你的代码在分割每行时直接访问components[0]和components[1],但以下情况会触发数组越界:
- TXT文件末尾存在空行(换行符分割出空字符串)
- 某行未遵循「日期 : 文本内容」格式,缺少「 : 」分隔符
- 行首/行尾的多余空格导致分割结果不符合预期
修复方案
- 过滤无效行:跳过空行,确保每行包含分隔符后再处理
- 安全访问数组元素:分割后先检查数组长度,避免直接索引越界
- 替换强制解包:用
do-catch处理文件读取异常,避免崩溃 - 优化日期格式化:给
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
相关产品推荐
相关产品推荐

