错误:Swift iOS中类型'Optional <NSMutableArray>'的值没有下标Array [0]

时间:2019-11-19 12:00:09

标签: ios arrays swift dictionary nsmutablearray

我正在从我的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)
     }

1 个答案:

答案 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)

请阅读以下内容: