简体   繁体   中英

Problem when an array element i'm trying to filter for does not exist

I have some code that gets a key from firebase, and compares it with a key stored locally in a text file. If there is a match, it checks an additional read/unread parameter, and then marks a variable as "Read" or "Unread".

The code works fine as long as every key I pull from Firebase exists in the text file. However, I get an "Index out of bounds" crash if a key from Firebase does not exist in my local file.

The code in question is as per below:

func readFile(){

    let filename = getDocumentsDirectory().appendingPathComponent("output.txt")
    do {

        let textStringFromFile = try String(contentsOf: filename, encoding: .utf8)

        var result: [(messageID: String, readStatus: String)] = []

        let rows = textStringFromFile.components(separatedBy: "\n")
        for row in rows {
            let columns = row.components(separatedBy: ",")
            result.append((columns[0], columns[1]))
        }


        let filteredMessageID = result.filter { $0.messageID == (nominationKeyForReadStatus) }

        var messageIDElement = filteredMessageID.map { $0.messageID }
        var readStatusElement = filteredMessageID.map { $0.readStatus }

        if readStatusElement[0] == "1" && nominationKeyForReadStatus == messageIDElement[0] {

            readStatusFromFunction = "Read"
        }
        else {
            readStatusFromFunction = "Unread"
        }
    }
    catch{

        }

    }

The crash seems to happen when filteredMessageID has 0 values. How do I account for this case? Thanks in advance.

You can make a pre check before accessing the index for messageIDElement , readStatusElement and filteredMessageID that it not having count 0.

if filteredMessageID.count != 0 {
   if readStatusElement.count != 0 && messageIDElement != 0 {
    // Your code
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM