致命错误:意外发现为nil

时间:2018-07-03 00:24:46

标签: swift

我的应用程序遇到问题。我正在使用func importPhoneBookContact,并获得:

  

致命错误:解开可选值时意外发现nil

当我在以下位置运行应用程序时:

cnContacts.remove(at: cnContacts.index(of: contact)!)

如何将nil字符串发送到函数?

func importPhoneBookContact(){
    let keysToFetch = [
        CNContactGivenNameKey, // Formatter.descriptorForRequiredKeys(for: .fullName),
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey] as [CNKeyDescriptor]
    let request = CNContactFetchRequest(keysToFetch: keysToFetch)
    var cnContacts = [CNContact]()
    var phoneNumbers = [String]()
    let phoneNumberKit = PhoneNumberKit()
    let store = CNContactStore()
    do {
        try store.enumerateContacts(with: request){ (contact, cursor) -> Void in
            cnContacts.append(contact)
        }

        if cnContacts.count > 0 {
            for contact in cnContacts {
                if contact.phoneNumbers.count > 0 {
                    for phone in contact.phoneNumbers{
                        if PFUser.current() == nil {
                            return
                        }

                        var phoneNumber = phone.value.stringValue
                        phoneNumber = phoneNumber.components(separatedBy: .whitespaces).joined()

                        if (phoneNumber.count) > 3 {
                            if String(phoneNumber[..<phoneNumber.index(phoneNumber.startIndex, offsetBy: 2)]) == "00" {
                                phoneNumber = "+"+String(phoneNumber[phoneNumber.index(phoneNumber.startIndex, offsetBy: 2)...])
                            } else if String(phoneNumber[..<phoneNumber.index(phoneNumber.startIndex, offsetBy: 1)]) != "+" {
                                if let code = (PFUser.current() as! User).countryCode {
                                    phoneNumber = "+"+String(describing: phoneNumberKit.countryCode(for: code)!)+phoneNumber
                                }
                            }
                        }

                        if phoneNumbers.contains(phoneNumber){
                            cnContacts.remove(at: cnContacts.index(of: contact)!)
                        } else{
                            phoneNumbers.append(phoneNumber)
                        }
                    }
                }
            }

            AppDelegate.contacts = cnContacts
            print("phone book contacts: ", AppDelegate.contacts.count)
        }
    } catch let error {
        NSLog("Fetch contact error: \(error)")
        AppDelegate.contactsImported = true
    }
}

1 个答案:

答案 0 :(得分:0)

正如@John Montgomery所指出的那样,在循环中永远不要改变数组。 因此,我建议不要维护要删除的对象数组,最后不要删除它们,而是不要在循环时删除对象。 以下是我的更新版本。

func importPhoneBookContact(){
    let keysToFetch = [
        CNContactGivenNameKey, // Formatter.descriptorForRequiredKeys(for: .fullName),
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey] as [CNKeyDescriptor]
    let request = CNContactFetchRequest(keysToFetch: keysToFetch)
    var cnContacts = [CNContact]()
    var phoneNumbers = [String]()
    let phoneNumberKit = PhoneNumberKit()
    let store = CNContactStore()
    var contactsToRemove = [CNContact]()
    do {
        try store.enumerateContacts(with: request){ (contact, cursor) -> Void in
            cnContacts.append(contact)
        }

        for contact in cnContacts {
            if contact.phoneNumbers.count > 0 {
                for phone in contact.phoneNumbers{
                    if PFUser.current() == nil {
                        return
                    }

                    var phoneNumber = phone.value.stringValue
                    phoneNumber = phoneNumber.components(separatedBy: .whitespaces).joined()

                    if phoneNumber.count > 3 {
                        if phoneNumber.prefix(2) == "00" {
                            phoneNumber = "+"+String(phoneNumber[phoneNumber.index(phoneNumber.startIndex, offsetBy: 2)...])
                        } else if phoneNumber.prefix(1) != "+",
                            let user = PFUser.current(),
                            let code = user.countryCode,
                            let countryCode = phoneNumberKit.countryCode(for: code) {
                            phoneNumber = "+"+countryCode+phoneNumber
                        }
                    }

                    if phoneNumbers.contains(phoneNumber) {
                        contactsToRemove.append(contact)
                    } else {
                        phoneNumbers.append(phoneNumber)
                    }
                }
            }
        }
        cnContacts = cnContacts.filter({ contactsToRemove.contains($0) })
        AppDelegate.contacts = cnContacts
        print("phone book contacts: ", AppDelegate.contacts.count)
    } catch let error {
        NSLog("Fetch contact error: \(error)")
        AppDelegate.contactsImported = true
    }
}