I sure would appreciate some assistance. I'm using Swift 5.1. What I'm attempting is to get the current date (date4) and format it to a three letter month abbreviation. No issue that part works fine. Then I define a constant called (currentMonthDate) that holds the concatenation of the three letter month and the string "MoonData". The result looks like this: "FebMoonData" - Up to this point all works as designed.
My Json is separated by month. Shown below is two months worth of Json as an abbreviated example. Obviously my model is designed to to accommodate the Json structure - not included. Now the issue. If you look at the JSONDecoder line of code you'll notice that I'm attempting to use the concatenation string "currentMonthDate" in the decoder line of code. My thought being that as each new month arrives data4 will be change and currentMonthDate will reflect that change and will then find the JSON block of data that reflects that particular month. The error I'm receiving is: Cannot convert value of type 'String' to expected argument type 'Data' For the sake of clarity if I simply type FebMoonData (name of the Json block for Feb) in the decoder line it works as expected. That is, it finds the Json array titled FebMoonData. Thank you!
// JSON
let FebMoonData = """
[
{"time":"20 Feb 2020 00:00 UT"}
]
""".data(using: .utf8)!
let MarMoonData =
[
{"time":"20 Feb 2020 00:00 UT"}
]
""".data(using: .utf8)!
// End JSON
let date4 = Date()
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "MMM"
let currentMonthDate = dateFormatterGet.string(from: date4) + "MoonData"
let moonphase = try! JSONDecoder().decode([MoonPhase].self, from: currentMonthDate)
The from
parameter of decode
must be Data
, not String
, this is the message of the error. The literal date string as JSON data makes no sense anyway. It's impossible to compose variable names at runtime.
What you can do is
let month = Calendar.current.component(.month, from: Date())
let data : Data
switch month {
case 1: data = Data(JanMoonData.utf8)
case 2: data = Data(FebMoonData.utf8)
// ...
}
let moonphase = try! JSONDecoder().decode([MoonPhase].self, from: data)
or
let month = Calendar.current.component(.month, from: Date())
let moonJSON : String
switch month {
case 1: moonJSON = JanMoonData
case 2: moonJSON = FebMoonData
// ...
}
let moonphase = try! JSONDecoder().decode([MoonPhase].self, from: Data(moonJSON.utf8)
or
let moonJSONArray = [JanMoonData, FebMoonData, MarMoonData, ..., DecMoonData]
let month = Calendar.current.component(.month, from: Date())
let moonJSON = moonJSONArray[month - 1]
let moonphase = try! JSONDecoder().decode([MoonPhase].self, from: Data(moonJSON.utf8)