[英]How to make an array using dummy values from Struct Modal class in Swift iOS
I am getting a JSON from my server.我从我的服务器获得了 JSON。 To parse the JSON, I am using Decoder and converting the data in my Modal Class object.
为了解析 JSON,我使用解码器并转换模态 Class object 中的数据。
This is my Modal class for Decoder:这是我的解码器模态 class:
struct SyncModelRecord : Codable {
var date : String
var shakeState : Int
}
class SyncModel {
var date : Date
var shakeState : Int
init?(record: SyncModelRecord) {
guard let secondsFrom1970 = Double(record.date) else {
return nil
}
date = Date(timeIntervalSince1970: secondsFrom1970)
shakeState = record.shakeState
}
}
My parsing is working fine.我的解析工作正常。
My problem is that now I have to make a 'SyncModelRecord' dummy array like:我的问题是现在我必须制作一个“SyncModelRecord”虚拟数组,例如:
var dummySyncModelRecordArray = [SyncModelRecord]()
var syncModelRecord : SyncModelRecord?
syncModelRecord?.shakeState = 0
syncModelRecord?.date = String(Int64(syncTimestamp!))
dummySyncModelRecordArray.append(syncModelRecord!)
But this is not working.但这不起作用。 Its crashing with Error (Please see the below attached error screenshot).
它因错误而崩溃(请参阅下面附加的错误屏幕截图)。
Please advise me.请给我提意见。
You're force unwrapping a value that is nil syncModelRecord
.您强制解开一个值为 nil
syncModelRecord
的值。
You need to instantiate it when declaring it.声明时需要实例化它。
var syncModelRecord: SyncModelRecord? = SyncModelRecord()
Or, even better, don't declare it as an optional, since you know at that point that it will not be nil
(if instantiated correctly, of course):或者,更好的是,不要将其声明为可选项,因为此时您知道它不会为
nil
(当然,如果实例化正确):
var syncModelRecord = SyncModelRecord()
You need to actually initialize syncModelRecord
.您需要实际初始化
syncModelRecord
。 Try this:尝试这个:
let syncModelRecord = SyncModelRecord(date: String(Int64(syncTimestamp!)), shakeState: 0)
dummySyncModelRecordArray.append(syncModelRecord!)
Another tip maybe worth exploring, you can directly decode a date and specify the decoder's strategy for it (in your case secondsSince1970
)另一个提示可能值得探索,您可以直接解码日期并为其指定解码器的策略(在您的情况下
secondsSince1970
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.