gpt4 book ai didi

ios - 错误: value of type 'Optional' has no subscripts Array[0] in Swift iOS

转载 作者:行者123 更新时间:2023-11-29 05:18:26 26 4
gpt4 key购买 nike

我正在从 Objective C 类中获取一些数据。这是我的“dataArray”数据:

Optional(<__NSArrayM 0x2818cff60>(
{
date = 1574164423;
shakeState = 1;
},
{
date = 1574164431;
shakeState = 1;
}
)
)

我创建了一个模态类“ShakeInfo”,其中包含日期和 shakeState 值。

我只想将此数组转换为“ShakeInfo”对象数组。我的问题是当我尝试打印“dataArray[0]”时出现错误:

error: <EXPR>:3:1: error: value of type 'Optional<NSMutableArray>' has no subscripts
dataArray[0]

如何按索引读取该数组值。请多多指教。

编辑:

这是我获取 dataArray 后的代码:

do {
let data = try JSONSerialization.data(withJSONObject: dataArray!)
let responseStr = String(data: data, encoding: .utf8)!

print(responseStr)//[{"date":"1574164424","shakeState":1},{"date":"1574164430","shakeState":1}]

var shakeInfoDetails = [ShakeInfo]()

//how to add 'responseStr' value in the shakeInfoDetails Modal Array

} catch {

print("JSON serialization failed: ", error)
}

最佳答案

let data = #"[{"date":"1574164424","shakeState":1},{"date":"1574164430","shakeState":1}]"#.data(using: .utf8)!

//Model

struct ModelRecord : Codable {

var date : String
var shakeState : Int
}

class Model {

var date : Date
var shakeState : Int

init?(record: ModelRecord) {

guard let secondsFrom1970 = Double(record.date) else {
return nil
}

date = Date(timeIntervalSince1970: secondsFrom1970)
shakeState = record.shakeState
}
}

//Decoding

let decoder = JSONDecoder()

do {
let records = try decoder.decode([ModelRecord].self, from: data)

let models = records.compactMap { Model(record: $0) }

}
catch {
print("Decoding Error: \(error)")
}

原始问题的答案:

let a1 : NSMutableArray? = NSMutableArray(array: ["A", "B", "C"])

a1?.object(at: 2)

请阅读以下内容:

关于ios - 错误: value of type 'Optional<NSMutableArray>' has no subscripts Array[0] in Swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58933640/

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