1

I would like to create an array of dates (or of tuples including an index and a data) from the following JSON.

My code is creating an array but instead of creating an array of dates, it breaks up the dates into characters. What do I need to do to create an array just of dates.

JSON looks like:

let json = """
    [{"date":"2017-01-05",
     "price":119.34},{"date":"2017-01-06",
     "price":118.93}];

Code is:

let myprices = try JSONDecoder().decode([Prices].self, from: Data(json.utf8))
let dates = myprices.sorted{$0.date < $1.date}.enumerated().map {Array($0.element.date)}

Code prints to console as:

dates [["2", "0", "1", "7", "-", "0", "1", "-", "0", "5"], ["2", "0", "1", "7", "-", "0", "1", "-", "0", "6"], ["2", "0", "1", "7", "-", "0", "1", "-", "0"]]

Thanks in advance for any suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44

1 Answers1

2

Replace

let dates = myprices.sorted{$0.date < $1.date}.enumerated().map {Array($0.element.date)}

with

let dates = myprices.sorted{$0.date < $1.date}.map { $0.date }

Currently you may be making let data:String change it to let date:Date and supply a formatter to the decoder check This

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • Yes. This fixed the problem. Thanks for tip about date decoding. In this case, I am decoding date as a string let date: String which I think this is okay because I am using date as a label--not doing any date calculations – user6631314 Jul 14 '20 at 13:23