2

Currently I'm letting users import a CSV-file created from Excel or Numbers. The sheet has multiple fields and I can import these without problem.

However, one of the fields looks like this:

"[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

How should I separate this field into a dictionary looking like this:

//[String: [[Int: String]]]

[
    "Title1": [[100: "S11"], [100: "S12"], [100:   "10"], [100:   "2"], [100:   "3"]],
    "Title2": [[300:  "50"], [300:  "90"], [300: "100a"], [300:   "D"], [300:   "E"]],
    "Title3": [[500:   "2"], [500: "112"], [500:    "6"], [500: "110"], [500: "113"]]
]

This field is created by the user itself and this already seems to be a bit too complicated and prone to error's. Perhaps a better question would be how to format this better instead of splitting this field into the dictionary I want?


Perhaps a simplified version:

//[String: [Int: [String]]]

[
    "Title1": [100: ["S11", "S12",   "10",   "2",   "3"]],
    "Title2": [300:  ["50",  "90", "100a",   "D",   "E"]],
    "Title3": [500:   ["2", "112",    "6", "110", "113"]]
]

Some explanation about this field:

Title: can be anything, it's the title of the nested dictionary

The key in the nested dictionary can be 100, 200, 300, 400, 500 or 600

The value in the nested dictionary is a String which forms a unique key together with they key in this nested dictionary.

This means:

100: "S11" and 200: "S11" // valid
100: "S11" and 100: "S11" // not valid

extension String {

    // Separate alphanumeric characters
    func split(_ number: Int = 1) -> [String] {
        let number = max(number, 1)

        return self.components(separatedBy: CharacterSet.alphanumerics.inverted).filter { $0.characters.count > number - 1 }
    }
}

let string = "Appetizer: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3) * Main: (300: 50), (300: 90), (300: 100a), (300: D), (300: E) * Dessert: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)"

let values = string.components(separatedBy: "*").map { $0.split() }

var result: [String: [Int: [String]]] = [:]

values.forEach {
    guard let key = $0.first else { return }

    result[key] = result[key] ?? [:]

    let values = $0.dropFirst()

    let name = values.enumerated().filter { $0.0 % 2 == 0 }.map { $0.1 }
    let code = values.enumerated().filter { $0.0 % 2 != 0 }.map { $0.1 }

    zip(name, code).forEach {
        guard let category = Int($0.0) else { return }

        result[key]?[category] = (result[key]?[category] ?? []) + [$0.1]
    }
}

This code produces the result I wanted, but it seems very ugly and it's too much dependant on the location of the values (instead of checking the values).

Any suggestion on how to do this using a much simpler and more elegant way?

5
  • You should define a structure to hold this data. Using array and dict will become confusing real fast. What do (100: S11), (100: S12) represent? Commented Apr 2, 2017 at 2:32
  • I will create a struct (or rather a NSManagedObject since I'll have to save this in CoreData). (100: S12) represents (Int: String) where 100 represents the category and S12 the identifier.
    – Henny Lee
    Commented Apr 2, 2017 at 2:36
  • I think you to seriously rethink your Excel template. Exporting to plain text is bad enough. Having it nested is even worse. And your solution won't work if there's a space in the category name, like "Today's Special" Commented Apr 2, 2017 at 3:30
  • @CodeDifferent: That's what I was afraid for. The only reason I'm letting users using an Excel to import is because I need at least 1 way of letting them import their menu into the app. The other fields only consist of 1 "string" so that should be fine (although I need to check if they're truly "unique". The field in this question however is to create a "full menu" with choices to choose from. In normal circumstances they don't need to specify this but they can. Also I really want it to keep it in 1 CSV file so I can also use the same format to export.
    – Henny Lee
    Commented Apr 2, 2017 at 8:36
  • This being said, any suggestion what else I could use considering these limitations? Also I'm thinking of using NSRegularExpression to achieve the result instead, so I can put the title in parentheses and items in brackets.
    – Henny Lee
    Commented Apr 2, 2017 at 8:39

2 Answers 2

0

The following code should parse the data you've provide into a dictionary as you wanted:

    let data = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"

    let arr1 = data.components(separatedBy:"],")
    var dic = [String:[[String:Any]]]()
    for row1 in arr1 {
        let arr2 = row1.components(separatedBy:",")
        var key = ""
        for row2 in arr2 {
            var txt = row2.replacingOccurrences(of:" ", with:"")
            if txt.hasPrefix("[Title") {
                // First row
                txt = txt.replacingOccurrences(of:"[", with:"")
                let arr3 = txt.components(separatedBy:":")
                key = arr3[0]
                let key1 = arr3[1].replacingOccurrences(of:"(", with:"")
                let val1 = arr3[2].replacingOccurrences(of:")", with:"").replacingOccurrences(of:" ", with:"")
                dic[key] = [[key1:val1]]
            } else {
                let arr3 = row2.components(separatedBy:":")
                let key1 = arr3[0].replacingOccurrences(of:"(", with:"").replacingOccurrences(of:" ", with:"")
                let val1 = arr3[1].replacingOccurrences(of:")", with:"").replacingOccurrences(of:"]", with:"").replacingOccurrences(of:" ", with:"")
                dic[key]?.append([key1:val1])
            }
        }
    }
    print(dic)

The above answers your first question, how do you parse the data you provided into a dictionary as you specified. The second question is a bit more complicated since I don't know enough about the data to provide a useful answer. But perhaps that is unnecessary now since the data can be split into a dictionary as required? :)

6
  • Thanks for the suggestion. This does indeed get the result I wanted. Still it feels like my data source is very prone to errors. Perhaps I should try to find a better way to create the source.
    – Henny Lee
    Commented Apr 2, 2017 at 2:34
  • That would be something where only you would know how best to go about things since we wouldn't have all the information. If my answer helped, please mark it as "correct". If you are looking at a different approach and this question is not relevant, then perhaps you might want to remove it?
    – Fahim
    Commented Apr 2, 2017 at 2:37
  • If you don't mind, ill keep this question open for a little longer. I've provided some more information about the source so perhaps it'll help the question a bit more. If not I'll just mark this as answered.
    – Henny Lee
    Commented Apr 2, 2017 at 2:44
  • It's your question, feel free to do whatever works for you :) But looking at it from my point of view, trying to answer the question as to how to set up the data source, I'd need to know what the source is and how it gives the data to your app? Is it an API endpoint that you control? If yes, is it possible to provide the data in JSON format? If the source is not in your control, then what are you actually looking for when you say that you must find a better way to create the source?
    – Fahim
    Commented Apr 2, 2017 at 2:52
  • Well, the source is coming from Excel (or Numbers). The user is suppose to be able to enter the information in Excel and export it to CSV so it can be imported to the app. So in short, the user can decide whatever format he wants to use (for now), but I'd like to keep it as simple as possible for the user and it's already far too complicated if you ask me :p.
    – Henny Lee
    Commented Apr 2, 2017 at 2:55
0

I assume that you settled on the first export format, i.e.

[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]

You can use RegEx to parse that string. The answer below does not handle errors. Also it will not work if you title contains a semicolon (:)

extension String {
    subscript(_ range: NSRange) -> String {
        let startIndex = self.utf16.index(self.utf16.startIndex, offsetBy: range.location)
        let endIndex = self.utf16.index(startIndex, offsetBy: range.length)

        return String(describing: self.utf16[startIndex..<endIndex])
    }
}

let str = "[Title1: (100: S11), (100: S12), (100: 10), (100: 2), (100: 3)], [Title2: (300: 50), (300: 90), (300: 100a), (300: D), (300: E)], [Title3: (500: 2), (500: 112), (500: 6), (500: 110), (500: 113)]"
let regex1 = try! NSRegularExpression(pattern: "\\[(.+?): (.+?)\\]", options: [])
let regex2 = try! NSRegularExpression(pattern: "\\((\\d+?): (.+?)\\)", options: [])

var result = [String: [Int: [String]]]()

regex1.enumerateMatches(in: str, options: [], range: NSMakeRange(0, str.utf16.count)) { match1, _, _ in
    guard let match1 = match1 else { return }

    let title = str[match1.rangeAt(1)]
    let categoriesStr = str[match1.rangeAt(2)]
    var categories = [Int: [String]]()

    regex2.enumerateMatches(in: categoriesStr, options: [], range: NSMakeRange(0, categoriesStr.utf16.count)) { match2, _, _ in
        guard let match2 = match2 else { return }

        let number = Int(categoriesStr[match2.rangeAt(1)])!
        let identifier = categoriesStr[match2.rangeAt(2)]

        if categories[number] == nil {
            categories[number] = [String]()
        }
        categories[number]!.append(identifier)
    }

    result[title] = categories
}

print(result)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.