-1

In my app I have a group of arrays that I append with data from an API. The method is as follows:

   let noOfCountries = APIData.data.count
            while self.countries < noOfCountries{
                self.idArray.append(APIData.data[self.countries].id!)
            self.countryIntroArray.append(APIData.data[self.countries].countryIntroTab!)
            self.countryNameArray.append(APIData.data[self.countries].countryName!)

            self.flagArray.append(APIData.data[self.countries].countryFlag!)

                self.countryEventsArray.append(APIData.data[self.countries].countryEventsTab!)// App crashes here with this error: Unexpectedly found nil while unwrapping an Optional value

                self.countries += 1
            }

For some reason the app crashes at at self.countryEventsArray.append. The arrays are declared as follows:

var idArray = [Int]()
var countryIntroArray = [String]()
var countryNameArray = [String]()
var flagArray = [String]()
var countryEventsArray = [String]()

The structs are set as such:

let id: Int?
let countryName: String?
let countryFlag: String?
let countryIntroTab: String?
let countryEventsTab: String?

What is it that I'm doing wrong? If I remove the exclamation from self.countryEventsArray the app will not run at all.

HamdyAli
  • 173
  • 3
  • 14

1 Answers1

0

you shouldn't append api data into array without any data exist check use the same code for check

if let myData = APIData.data[self.countries].countryEventsTab {
   self.countryEventsArray.append(myData)
}