Eric
Eric

Reputation: 91

Swift parse csv file for result based on input

I am asking the user to input three values: length, width, and weight

I am referencing a csv file to find results based on the input

Snippet of csv file:

Length,Width,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,Max2
14,6,16,13,11,9,8,7,6,6,5,5,5,4,4,6500
16,6,18,15,12,11,9,8,7,7,6,6,5,5,5,7400
...
34,7,46,37,31,26,23,20,18,17,15,14,13,12,11,18400

For example, if a user enters:

length: 14
width: 6
weight: 400

I need to display results based on the csv:

16
6,500

The csv file represents this table with the data, here is a snippet:

snippet of table that csv represents

Tan represents input values, blue represents output

How can I look through the csv file based on the input and find the exact results to display?

Upvotes: 1

Views: 692

Answers (1)

Code Different
Code Different

Reputation: 93141

I strongly recommend you to start at the data model first. The spreadsheet you show is what I call "pivoted" and is pretty hard to deal with at the application logic layer. Convert it into normalized data, which allows you to perform the operations you need.

struct DataModel {
    var length: Int
    var width: Int
    var weight: Int
    var maxWeight: Int
    var price: Int // Or whatever the data those teal cells represent
}

let csv = """
Length,Width,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,Max2
14,6,16,13,11,9,8,7,6,6,5,5,5,4,4,6500
16,6,18,15,12,11,9,8,7,7,6,6,5,5,5,7400
34,7,46,37,31,26,23,20,18,17,15,14,13,12,11,18400
"""

let lines = csv.components(separatedBy: "\n")
let headers = lines[0].components(separatedBy: ",")
var lookupData = [DataModel]()

for line in lines[1...] {
    let columns = line.components(separatedBy: ",")
    let length = Int(columns[0])!
    let width = Int(columns[1])!
    let maxWeight = Int(columns.last!)!

    for (index, column) in columns.enumerated() where ![0,1,columns.count - 1].contains(index) {
        let weight = Int(headers[index])!
        let price = Int(column)!
        lookupData.append(DataModel(length: length, width: width, weight: weight, maxWeight: maxWeight, price: price))
    }
}

// Now you can search for the user's inputs easily
print(lookupData.filter { $0.length == 14 && $0.width == 6 && $0.weight == 400 })

The code in for Swift 4 and does not check for data validity. It assumes that everything is correct and in the expected format. Customize as needed.

Upvotes: 2

Related Questions