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

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


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: Doublevar d20170101: Doublevar 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.


You can parse your json dictionary as [String:Double] and them convert it to a tuple array of date and double:

let json = """{"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}"""

let dateFormatter = DateFormatter()dateFormatter.dateFormat = "yyyyMMdd"dateFormatter.locale = Locale(identifier: "en_US_POSIX")  

do {    let array: [(date: Date, double: Double)] = try JSONDecoder().decode([String:Double].self, from: Data(json.utf8))        .compactMap({ key, value in        guard let date = dateFormatter.date(from: key) else { return nil }        return (date, value)    }).sorted(by: { $0.date < $1.date })    for (date, double) in array {        print("Date:", dateFormatter.string(from: date), "• Value:", double)    }} catch {    print(error)}

Date: 20170101 • Value: 0.17

Date: 20170102 • Value: 1.0

Date: 20170103 • Value: 0.68

Date: 20170104 • Value: 0.61

Date: 20170105 • Value: 1.03

Date: 20170106 • Value: 0.48

Date: 20170107 • Value: 0.52

Date: 20170108 • Value: 0.51

Date: 20170109 • Value: 0.28