Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift JSON variables with all numeric names. What's the work around?

I am pulling some JSON data that I need to parse using Decodable into Swift.

As most of the data is dates I have 365 date entries along the lines of:

"20170101": 0.17, 
"20170102": 1.0, 
"20170103": 0.68, 
"20170104": 0.61, 
"20170105": 1.03, 
"20170106": 0.48, 
"20170107": 0.52, 
"20170108": 0.51, 
"20170109": 0.28, 

When I am generating the relevant struct to absorb the data how to I create a variable with a what appears to be a numeric name:

var 20170101: Double

What, and is there, a workaround to having a numeric name?

like image 528
Edward Hasted Avatar asked Sep 18 '25 14:09

Edward Hasted


2 Answers

You' re not allowed to use digits as first letter of properties name. But sometimes we have to use digits as you've shown in your code.

Solution of that problem is using CodingKey protocol with Enumerations like below:

enum CodingKeys: String, CodingKey {
    case date = "20170101" // You can use "date" instead of "20170101".
}
like image 140
Mansa Pratap Avatar answered Sep 20 '25 06:09

Mansa Pratap


Variable names can’t begin with a number (although you can use numbers later in the name). They must start with a letter or an underscore _:

var _20170101: Double
var d20170101: Double
var d_20170101: Double

In Swift (as with other languages) variable names cannot contain whitespace characters, mathematical symbols (such as the plus (+) or minus (-) operators) or certain Unicode values or line and box drawing characters.The main reason for this is to ensure that the Swift compiler is able understand where the names of our variables start and where they finish.

Other than that, when naming a variable:

  • Strive for clarity

  • Prioritize clarity over brevity

  • Name variables, parameters, and associated types according to their roles

For more details on naming conventions, have a look here.

like image 25
ielyamani Avatar answered Sep 20 '25 07:09

ielyamani