我正在从我的Objective C类中获取一些数据。这是我的“ dataArray”数据:
Optional(<__NSArrayM 0x2818cff60>(
{
date = 1574164423;
shakeState = 1;
},
{
date = 1574164431;
shakeState = 1;
}
)
)
我创建了一个Modal类'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)
请阅读以下内容:
Swift中的可选项
可编码-https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
Swift标准库中的数组
在Foundation中定义的NSMutableArray
关于ios - 错误:Swift iOS中类型'Optional <NSMutableArray>'的值没有下标Array [0],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58933640/