0

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
}
4
  • Did you try to debug this or add print statements to see what is going on? My guess is that you have a \n at the end so you get an extra empty line and it is for this empty line you get the exception. Try to add if row.isEmpty { continue } as the first line in your for loop. Commented Nov 13, 2020 at 15:09
  • I fixed it by replacing ",\n" with "\n" to remove empty objects in array Commented Nov 14, 2020 at 5:43
  • Good but why did you mark the answer below as accepted then? Commented Nov 14, 2020 at 9:08
  • The below comment fixed index out of bound error Commented Nov 14, 2020 at 9:27

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried but the thing is every array has 6, because there is a "" if the field is empty

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.