无法从通用函数中的 CNMutableContact 中删除项目

Unable to remove item from CNMutableContact in Generic Function

我想允许用户在显示原始联系人后从联系人中删除元素(例如 CNPhoneNumberCNEmailAddresses),并根据他们的选择从我编辑的联系人中删除。

即使我有一个可变联系人并使用我代码中键的可变数组,返回的已编辑联系人也不会删除该元素。

我做错了什么?

这是我的通用函数(构建和运行良好,除了上面列出的问题)

private func removeFromEditedContact<T:NSString>(labeledValueType:T, with key:String,from contact:CNContact,to toContact:CNContact, at indexPath:IndexPath) -> CNContact {

    let mutableContact = toContact.mutableCopy() as! CNMutableContact


    //what detail are we seraching for in the contact
    if let searchingArray = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>] {
        let searchValue = searchingArray[indexPath.row].value
        //if detail is present in our mutable contact remove it
        var labeledValueToChange = mutableContact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>]

        if let index = labeledValueToChange?.index(where: {[=10=].value == searchValue})  {
            labeledValueToChange?.remove(at: index)

        }
    }
    return mutableContact
}

联系人未被修改,因为您只是从您创建的可变数组中删除值。从 labeledValueToChange 中删除此值后,您必须将其重新分配给联系人,如下所示:

contact.setValue(labeledValueToChange, forKey: key)

此外,如果原始联系人是您要修改的联系人,您可以直接将其作为 inout 参数传递给函数。我试过你的功能,它是这样工作的:

private func removeFromEditedContact<T:NSString>(labeledValueType:T, with key:String,from contact:inout CNMutableContact, at indexPath:IndexPath) -> CNMutableContact {

        //what detail are we seraching for in the contact
        if let searchingArray = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>] {

            let searchValue = searchingArray[indexPath.row].value
            //if detail is present in our mutable contact remove it
            var labeledValueToChange = contact.mutableArrayValue(forKey: key) as? [CNLabeledValue<T>]

            if let index = labeledValueToChange?.index(where: {[=11=].value == searchValue})  {
                labeledValueToChange?.remove(at: index)
            }


            contact.setValue(labeledValueToChange, forKey: key)
        }

        return contact
    }