Youngho Kim
Youngho Kim

Reputation: 205

Adding string to array

When i am parsing through the string from the url, I append each new line to an array. However I only want to add if the field is not empty. So if the column[5] is an empty string I don't append it to the array. For example I have two lines of strings:

1,2,3,4,5,

1,2,3,4,5,6

I only want to append when there are 6

However I am getting a index out of range error on the if column[5] == "" line

func readDataFromURL(url: String) -> String?{
    if let url = URL(string: url)
        {
        do {
            var contents = try String(contentsOf: url)
            contents = contents.replacingOccurrences(of: "\r", with: "")
            csv(data: contents)
            return contents
        } catch {
            print("File error \(url)")
            return nil
        }
    }
    return nil
}

func csv(data: String) -> [[String]] {
    var result: [[String]] = []
    let rows = data.components(separatedBy: "\n")
    for row in rows {
        let columns = row.components(separatedBy: ",")
        if columns[5] == "" {
            continue
        } else {
            result.append(columns)
        }
    }
    return result
}

Upvotes: 0

Views: 94

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Your current code will crash if num of elements is less than 6 , Replace

if columns[5] == "" {
    continue
} else {
    result.append(columns)
}

with

if columns.count > 5 && columns.last != "" {
  result.append(columns)
}

Upvotes: 1

Related Questions