我正在从我的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)
}
答案 0 :(得分:0)
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)