-2

I have Codable Model like this

struct Payment: Codable {
  var id: Int?
  var date: String?
  var companyId: Int?
  var companyName: String?
  var dueDate: String?
  var amount: Int?
  var paidOrNot: Bool?
  var paidDate: String?
  var returnAmount: Int?
  var paidAmount: Int?
  var createdAt: String?
  var updatedAt: String?
}

When I print encoded data from the dictionary, there are optionals in my httpBody.

Payment(id: nil, 
        date: Optional("Nov 23, 2018"), 
        companyId: nil, companyName: Optional(""), 
        dueDate: Optional("Nov 23, 2018"), 
        amount: Optional(5), 
        paidOrNot: Optional(true), 
        paidDate: Optional("Nov 23, 2018"), 
        returnAmount: Optional(0), 
        paidAmount: Optional(5), 
        createdAt: nil, 
        updatedAt: nil)
Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
Andreas
  • 45
  • 7
  • Of course there are as all struct members are declared as optionals. It could be a misuse of `String Interpolation` or `String(describing` – vadian Nov 23 '18 at 09:44
  • What do you want to achieve? – Nilanshu Jaiswal Nov 23 '18 at 09:46
  • This should help you to understand why Optional(xxx) is printed: https://stackoverflow.com/questions/25846561/printing-optional-variable – Robert Dresler Nov 23 '18 at 09:46
  • @Damon I'm trying to make a POST request and now all optionals become String when it should be Int – Andreas Nov 23 '18 at 10:36
  • @Andreas Please show where the optionals have become String. In the encoded data you have shared, I can't find any. – Nilanshu Jaiswal Nov 23 '18 at 10:49
  • @Andreas you can use the function JsonSerialization.jsonObject(with:data, options: .allowFragments) to convert the Data object you serialized in the first place – jms Nov 23 '18 at 11:24
  • @Damon oh sorry, not string, maybe I think optional(“”) didn’t go well in database column type Int. – Andreas Nov 23 '18 at 11:30
  • @jms I know how to serialize, but the problem is optional – Andreas Nov 23 '18 at 11:31
  • You should not worry about optional. It will automatically be handled. You can check the values in Postman. – Nilanshu Jaiswal Nov 23 '18 at 11:33
  • @Andreas the way you put the question makes me feel like the POST request body comes as something like {id: nil, date: "Optional("Nov 23, 2018")", ...}. Can you confirm this (printing the object to be encoded will not help). Instead try serializing the data you encoded to ensure that this is actually the case. – jms Nov 23 '18 at 11:36
  • Haha, bro you sounds understand so much with the part “solve main problem”. I just solved RN. If I cant, I have to ask you. It was solved by your gratitude @jms :D – Andreas Nov 23 '18 at 12:21

1 Answers1

0

Writing var id: Int? makes the type Integer optional. This just means that the program will not end if this was detected as empty. The program will continue.

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34