Arrays Swift:如何向JSON数组添加多个项?
我正在尝试在Swift中为命令行创建一个基本的待办事项应用程序。下面是我向待办事项数组添加新项的函数,但新项会不断覆盖旧项,而不是创建新项。最后,Arrays Swift:如何向JSON数组添加多个项?,arrays,json,swift,codable,Arrays,Json,Swift,Codable,我正在尝试在Swift中为命令行创建一个基本的待办事项应用程序。下面是我向待办事项数组添加新项的函数,但新项会不断覆盖旧项,而不是创建新项。最后,todo.json文件中只有一个条目 当我将输入项和.append语句相乘时,它会自动工作,但可能是我的大脑已经死了,现在还无法理解它 结构TodoItem:可编码{ let name:String } 变量todoList=[TodoItem]() func addToList(uItem:String)->String{ 让todoItem=to
todo.json
文件中只有一个条目
当我将输入项和.append
语句相乘时,它会自动工作,但可能是我的大脑已经死了,现在还无法理解它
结构TodoItem:可编码{
let name:String
}
变量todoList=[TodoItem]()
func addToList(uItem:String)->String{
让todoItem=todoItem(名称:项)
todoList.append(todoItem)
做{
让fileURL=try FileManager.default
.url(用于:.applicationSupportDirectory,
在:.userDomainMask中,
适用范围:无,
创建:true)
.appendingPathComponent(“示例”)
.appendingPathExtension(“json”)
let encoder=JSONEncoder()
尝试编码器.encode(todoList).write(到:fileURL)
}抓住{
返回“Error:\(Error.localizedDescription)”
}
return“添加的项目:\(todoItem.name)”
}
您的代码工作正常。我认为问题在于,运行此命令时,todoList
是空的。但您可以编写代码来检索JSON的内容:
var todoList: [TodoItem] = []
func retrieveToDoList() {
guard let data = try? Data(contentsOf: fileURL) else { return }
todoList = (try? JSONDecoder().decode([TodoItem].self, from: data)) ?? []
}
因此,例如,考虑:
retrieveToDoList()
addToList("foo")
addToList("bar")
addToList("baz")
print(todoList)
// if you want to check the json
let data = try! Data(contentsOf: fileURL)
let json = String(data: data, encoding: .utf8)!
print(json)
这导致:
[MyApp.TodoItem(name: "foo"), MyApp.TodoItem(name: "bar"), MyApp.TodoItem(name: "baz")]
[
{
"name" : "foo"
},
{
"name" : "bar"
},
{
"name" : "baz"
}
]
然后我得到:
[
{
"name" : "foo"
},
{
"name" : "bar"
},
{
"name" : "baz"
},
{
"name" : "abc"
},
{
"name" : "def"
},
{
"name" : "hij"
}
]
您是否调试了代码,在调用函数之前是否确定todoList包含任何内容?你有错误吗?是的,它肯定不是空的。我还多次运行该命令,我可以看到以前的条目,但它被替换为新条目。@fankibiber:请为第二个问题提出一个新问题。@koen,编辑了该部分。是的!谢谢你,现在我明白了。 [ { "name" : "foo" }, { "name" : "bar" }, { "name" : "baz" }, { "name" : "abc" }, { "name" : "def" }, { "name" : "hij" } ]
struct TodoItem: Codable {
let name: String
}
class ViewController: UIViewController {
private var todoList: [TodoItem] = []
private let fileURL = try! FileManager.default
.url(for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
.appendingPathComponent("example.json")
override func viewDidLoad() {
super.viewDidLoad()
retrieveToDoList()
addToList("foo")
addToList("bar")
addToList("baz")
print(todoList)
// if you want to check the json
let data = try! Data(contentsOf: fileURL)
let json = String(data: data, encoding: .utf8)!
print(json)
}
}
private extension ViewController {
func retrieveToDoList() {
guard let data = try? Data(contentsOf: fileURL) else { return }
todoList = (try? JSONDecoder().decode([TodoItem].self, from: data)) ?? []
}
@discardableResult
func addToList(_ item: String) -> String {
let todoItem = TodoItem(name: item)
todoList.append(todoItem)
do {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
try encoder.encode(todoList).write(to: fileURL)
} catch {
return "Error: \(error.localizedDescription)"
}
return "Item added: \(todoItem.name)"
}
}