应用程序在打印联系人姓名和号码的过程中崩溃

app crashes in the middle of printing contact names and numbers

这是我的代码,我的应用程序在打印数据的过程中崩溃,日志中没有错误消息。它打印了将近 30 个人,然后崩溃了,在崩溃的代码行上显示了这条消息:

Thread 1: EXC_BREAKPOINT (code=1, subcode =.....)

我将在我的代码中出现此消息的位置用 //CRASH 标记代码行:

import UIKit
import Contacts
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    for cont in contacts {
        print(cont.givenName)
        let num = ((cont.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue //CRASH
        print(num)
    }
    // Do any additional setup after loading the view, typically from a nib.
}

lazy var contacts: [CNContact] = {
    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
        CNContactEmailAddressesKey,
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey] as [Any]

    // Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containers(matching: nil)
    } catch {
        print("Error fetching containers")
    }

    var results: [CNContact] = []

    // Iterate all containers and append their contacts to our results array
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)

        do {
            let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
            results.append(contentsOf: containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}()

}

我以为我可能正在解包 nil 但事实并非如此,因为它不是可选的(我试图以安全的方式解包它,但编译器说它不是可选类型)。

来自评论:

问题原来是 cont.phoneNumbers.first?.value 的强制展开,因为如果没有 phone 个数字(因此没有第一个求值),它将为 nil。