I have model as below.
struc Info: Decodable {
var firstName: String?
var lastName: String?
}
While displaying in tableview cell, what I am doing is as below.
personName.text = "\(personArray[indexPath.row].firstName!) \(personArray[indexPath.row].lastName!)"
Now the app is crashing if I have data in below format
[
{
"firstName" : "F 1",
"lastName" : "L 1"
},
{
"firstName" : "F 2"
},
{
"lastName" : "L 3"
}
]
The app is crashing saying lastName is nil
Solution 1
The solution for this check for nil & then show name, however I don't want to do the check at run time because that I have to check this for all variables (considering I have model of 25 variables). Below is what I could have done.
var firstName = ""
if (personArray[indexPath.row].firstName == nil) {
firstName = ""
} else {
firstName = personArray[indexPath.row].firstName!
}
var lastName = ""
if (personArray[indexPath.row].lastName == nil) {
lastName = ""
} else {
lastName = personArray[indexPath.row].lastName!
}
personName.text = "\(firstName) \(lastName)"
Solution 2
I can do the update in the model itself as below.
struc Info: Decodable {
var firstName: String?
var lastName: String?
var firstName2 : String? {
get {
if (self.firstName==nil) {
return ""
}
return firstName
}
var lastName2 : String? {
get {
if (self.lastName==nil) {
return ""
}
return lastName
}
}
personName.text = "\(personArray[indexPath.row].firstName2!) \(personArray[indexPath.row].lastName2!)"
However I have problem with this also. This way, again I have to create N number of variables again.
Is there any other alternate way where default value will get assigned if that variable is missing in the webservice?