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

如何将文本文件加载至自定义结构体数组?附现有实现代码

如何将文本文件加载至自定义结构体数组?

嘿,我来帮你搞定把文本文件数据加载到Question结构体数组的事儿!目前你手动创建实例的方式虽然可行,但如果题目多了肯定麻烦,咱们换成从文件加载会高效很多。下面分两种常用的文本格式来给你演示:

方式一:用JSON格式(推荐,结构化数据更清晰)

首先,咱们得让Question结构体支持自动解析——Swift里的Codable协议正好能帮咱们搞定JSON和结构体的双向转换,先修改你的结构体:

struct Question: Codable { 
    let imgName: String 
    let questionText: String 
    let options: [String] 
    let correctAns: Int 
    var wrongAns: Int 
    var isAnswered: Bool 
} 
var questionsArray = [Question]() 

接下来,准备一个JSON文本文件(比如命名为questions.json),把题目数据按结构体的属性对应写成JSON数组:

[
    {
        "imgName": "img1",
        "questionText": "What is 2 x 2 ?",
        "options": ["2", "4", "8", "6"],
        "correctAns": 1,
        "wrongAns": -1,
        "isAnswered": false
    },
    {
        "imgName": "img2",
        "questionText": "What is 4 + 2 ?",
        "options": ["9", "4", "3", "6"],
        "correctAns": 3,
        "wrongAns": -1,
        "isAnswered": false
    }
]

记得把这个文件添加到你的Xcode项目里(确保勾选了对应的target)。

然后写代码加载并解析这个文件:

func loadQuestionsFromJSON() {
    guard let url = Bundle.main.url(forResource: "questions", withExtension: "json") else {
        print("找不到questions.json文件")
        return
    }
    
    do {
        let data = try Data(contentsOf: url)
        let decoder = JSONDecoder()
        questionsArray = try decoder.decode([Question].self, from: data)
        print("成功加载\(questionsArray.count)道题目")
    } catch {
        print("解析JSON失败:\(error.localizedDescription)")
    }
}

// 调用加载函数
loadQuestionsFromJSON()

方式二:用CSV格式(适合简单的表格型数据)

如果习惯用CSV(逗号分隔值)格式的文本文件,也可以这么做。先准备questions.csv文件,内容如下:

imgName,questionText,options,correctAns,wrongAns,isAnswered
img1,"What is 2 x 2 ?","2,4,8,6",1,-1,false
img2,"What is 4 + 2 ?","9,4,3,6",3,-1,false

注意:如果字段里包含逗号(比如options数组),要给整个字段加引号。

然后写解析代码:

func loadQuestionsFromCSV() {
    guard let url = Bundle.main.url(forResource: "questions", withExtension: "csv") else {
        print("找不到questions.csv文件")
        return
    }
    
    do {
        let content = try String(contentsOf: url)
        let lines = content.components(separatedBy: .newlines).filter { !$0.isEmpty }
        // 跳过表头行
        let dataLines = Array(lines.dropFirst())
        
        for line in dataLines {
            // 处理带引号的字段,这里用简单的分割逻辑,如果需求复杂可以用专门的CSV解析库
            let fields = line.components(separatedBy: "\",\"").map { $0.trimmingCharacters(in: CharacterSet(charactersIn: "\"")) }
            
            guard fields.count == 6 else {
                print("该行格式错误:\(line)")
                continue
            }
            
            let imgName = fields[0]
            let questionText = fields[1]
            let options = fields[2].components(separatedBy: ",")
            guard let correctAns = Int(fields[3]),
                  let wrongAns = Int(fields[4]),
                  let isAnswered = Bool(fields[5]) else {
                print("字段转换失败:\(line)")
                continue
            }
            
            let question = Question(imgName: imgName, questionText: questionText, options: options, correctAns: correctAns, wrongAns: wrongAns, isAnswered: isAnswered)
            questionsArray.append(question)
        }
        
        print("成功加载\(questionsArray.count)道题目")
    } catch {
        print("读取CSV失败:\(error.localizedDescription)")
    }
}

// 调用加载函数
loadQuestionsFromCSV()

两种方式里更推荐JSON,因为它天生支持数组、布尔值等类型,解析起来不容易出错;CSV适合简单场景,但要处理好特殊字符的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:23:47