I want to parse JSON object that receive from server. there is my code for parsing JSON and create object.
class Transaction {
var id: String!
var amount: String!
var balance: String!
var detail: String!
var serial: String!
var time : String!
var type: String!
init(id: String, amount: String, balance: String, detail:String, serial: String, time: String, type: String ) {
self.id = id
self.amount = amount
self.balance = balance
self.detail = detail
self.serial = serial
self.time = time
self.type = type
}
func CreateTransactionObject(json: [String:Any]) -> Transaction? {
guard let id = json["id"] as? String,
let amount = json["amount"] as? String,
let balance = json["balance"] as? String,
let detail = json["detail"] as? String,
let serial = json["serial"] as? String,
let time = json["time"] as? String,
let type = json["type"] as? String
else {
return nil
}
let object = Transaction(id: id, amount: amount, balance: balance, detail: detail, serial: serial, time: time, type: type)
return object
}
this work fine when guard statement don't return nil. for example when one of the parameters is null guard statement return nil and object can't create. how can parse JSON that if any object don't receive from server or get null ?
initmethod passing non-optional values. The properties work also (even better) without trailing exclamation or question mark.