【发布时间】:2019-02-23 14:55:25
【问题描述】:
我在读取本地 JSON 文件时遇到问题。当我想尝试在我的 parseJson() 中打印任何内容时,我的控制台中什么也没有出现。
这是我的 JSON 文件:
{
"questions":[
{
"question": "First Question ???",
"response": "First Response",
},
{
"question": "Second Question ???",
"response": "Second Response",
}
]
}
这是我的问题Result.swift
import Foundation
struct questionsResult: Decodable {
var questions: [Questions]
}
struct Questions: Decodable {
var question: String
var response: String
}
这是我在 ViewController 文件中的函数:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var questionsJson = [Questions]()
func parseJSON(){
if let url = Bundle.main.url(forResource: "test", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(questionsResult.self, from: data)
questionsJson.append(contentsOf: jsonData.questions)
print(url)
} catch {
print("Json error \(error)")
}
}
}
}
}
你能帮帮我吗?
【问题讨论】:
-
我看到了一些问题,
questionsJson被声明为不可变,并且您的函数将Data对象作为参数,但您也在从主包中读取文件。而且这个错误看起来像一个编译错误,是吗?
标签: swift