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?
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".
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With