mercredi 14 mars 2018

If Statement with Array Variables Out of Range

I'm trying to search a user's contacts but one of my if statements is broken. It checks if the character at a certain index of the input matches the character of the same index of the givenName, familyName, and phoneNumber. My problem is that sometimes the number of characters entered is more than the number of characters in the givenName, familyName, or phoneNumber. This makes my if statement compare the character at a certain index of the input and the character at an index that doesn't exist. For instance, it compares charInput[2] to charGivenName[2] but charGivenName only has values at charGivenName[0] and charGivenName[1]. Since charGivenName[2] doesn't exist, my apps crashes.

Does anyone know how to fix this?

@IBAction func contactTextFieldChanged(_ sender: Any) {
    if contactTextField.text != "" {

        contactTableView.isHidden = false

        let request = CNContactFetchRequest(keysToFetch: keys as! [CNKeyDescriptor])
        do {

            try contactStore.enumerateContacts(with: request){
                (contact, stop) in

                self.contacts.append(contact)

                for phoneNumber in contact.phoneNumbers {

                    if phoneNumber.value.stringValue != ""{

                        let charGivenName = Array(contact.givenName)
                        let charFamilyName = Array(contact.familyName)
                        let charNumber = Array(phoneNumber.value.stringValue)
                        let charInput = Array(self.contactTextField.text!)
                        var matchBool = false

                        for inputCount in (0...charInput.count - 1) {

                            if charNumber[inputCount] == charInput[inputCount] || charGivenName[inputCount] == charInput[inputCount] || charFamilyName[inputCount] == charInput[inputCount]{

                                matchBool = true

                            } else {

                                matchBool = false
                                break

                            }

                            if matchBool == true {

                                print("\(contact.givenName) \(contact.familyName) \(phoneNumber.value.stringValue)")

                            }
                        }
                    }
                }
            }
        } catch {

            print("Error fetching contacts")

        }
    }
    if contactTextField.text == ""{

        contactTableView.isHidden = true

    }
}

Aucun commentaire:

Enregistrer un commentaire