gpt4 book ai didi

swift - 使用 JSON 数组填充 Swift 数组

转载 作者:行者123 更新时间:2023-11-30 13:18:27 24 4
gpt4 key购买 nike

对 Swift 相当陌生,正在尝试弄清楚如何使用 JSON 数组的值填充 Swift 数组。

在我的类(class)中,我定义了以下值来保存图表 x 轴的值。

var xVal: [String]!

下面我尝试删除静态数组并将其替换为 JSON 文件中的数据。 xVal 尝试访问 JSON 文件,yVal 是静态的并且工作正常。 xVal 给出以下错误:无法使用“String”类型的索引为“JSON”类型的值添加下标

xVal = dataStatistics[indexPath.section]["xval"]
let yVal = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]

setChart(xVal, values: yVal)

JSON 文件的结构如下:

{
"statistics": [
{
"title": "Title of chart 1",
"description": "Chart one contains data of the last year",
"xval": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"yval": [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
}
]
}

最佳答案

根据输入的 json 数据,我假设 swiftyjsonstatistics 解析为另一种 json 类型。那你可以试试这个吗

let stats = dataStatistics[indexPath.section].dictionaryValue
xval = stats["xval"]

看看是否有效

关于swift - 使用 JSON 数组填充 Swift 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38009764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com