首页 > 解决方案 > 如何构建包含段落的可下载内容包?

问题描述

我正在制作一个闪存卡应用程序。每张闪存卡都有以下内容 - 一个主题 - 一个问题 - 一个答案

答案可以是多个段落,例如一篇短文。

例如:主题:营养问题:什么是古?答案:古是低碳水化合物饮食。\n 它依赖于特定的肉类和蔬菜作为饮食的主食。你不能在古代吃面包。

CSV 似乎不是一个选项,除非我将 \n 替换为 ~~

该段落中也可能有引号。我希望能够下载一包抽认卡以供离线使用,因此仅从数据库中提取并不适合于此。

有没有一种好的格式/结构可以用来捆绑一包抽认卡,以便在本地系统上轻松下载/解析/保存?

标签: iosswiftdata-structures

解决方案


您可以按如下方式表示您的数据:

struct Card: Codable {
    let topic: String
    let question: String
    let answer: String
}

然后,如果您有一个数组let card = [Card],您可以使用 a 转换为 JSON 并将 JSON 转换JSONEncoderCardusingJSONDecoder

let cards = [Card(topic: "Nutrition", question: "What is paleo?", answer: "Paleo is a low carb diet.\nIt relies on specific meats and vegetables as the staple of the diet. You cannot eat bread on paleo.")]

let data = try JSONEncoder().encode(cards)

let string = String(data: data, encoding: .utf8)!

print(string)

// [{"topic":"Nutrition","question":"What is paleo?","answer":"Paleo is a low carb diet.\nIt relies on specific meats and vegetables as the staple of the diet. You cannot eat bread on paleo."}]

let newCards = try JSONDecoder().decode([Card].self, from: data)

推荐阅读