0

So I have JSON data that's in an array (0 is first day of month up until last day of month).

How do I do a loop to go through the whole array and store the 3 times of the day each in their own array (I wish to use these times for notifications later)

The dayForArray variable is just the current day - 1 so that it matches the number in the JSON array.

func parseJSON(_ timesData: Data) -> TimesModel? {
    let decoder = JSONDecoder()
    do {
        let decodedData = try decoder.decode(TimesData.self, from: timesData)
        let time1 = decodedData.data[dayForArray].timings.Time1
        let time2 = decodedData.data[dayForArray].timings.Time2
        let time3 = decodedData.data[dayForArray].timings.Time3

        let time = TimeModel(time1: time1, time2: time2, time3: time3)

        return times

    } catch {
        delegate?.didFailWithError(error: error)
        return nil
    }
}
2
  • So, you're saying that this code works, but just for one day, dayForArray, and you want it to apply to each day in the month? Commented Mar 6, 2020 at 19:26
  • Yes it's working now. But it's only storing the current day's times and that's it. I'd like to grab the whole JSON array and store them so that I can notify users of these 3 time's throughout the day without having to check the app every day Commented Mar 6, 2020 at 19:36

1 Answer 1

1

What you need to do is to use map to create an array of TimeModel objects from your json array

let times = decodedData.data.map { 
    TimeModel(time1: $0.timings.Time1, 
              time2: $0.timings.Time2, 
              time3: $0.timings.Time3) 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok so I'm getting somewhere.. I added that but now got the error "Cannot convert return expression of type '[TimeModel]' to return type 'TimeModel?'" I thought this is because in my TimeModel I list the 3 times as Strings, I changed those to array (not sure if I should have?) and now I'm getting "Argument passed to call that takes no arguments". Thanks for the help
@MichaelScott your function is declared to return a TimeModel, change it to return an array [TimeModel]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.