从对象数组中删除对象 swift 3.



我正在尝试从对象数组中删除对象

尝试了不同的方案,但没有删除项目,而是将其添加到数组中 2 次,我疯了,找不到任何原因

 let pages = surveyData.pagerItems; // Pages is a model which contains an array of another model called question
 let questions = self.pages[indexPath.section].questionItems.filter{$0.id != questionId};
 self.pages[indexPath.section].questionItems = questions;

在将其分配给页面对象之前,我尝试先删除所有问题项

self.pages[indexPath.section].questionItems.removeAll();
self.pages[indexPath.section].questionItems = questions;

也试过这个

self.pages[sourceIndex.section].questionItems.remove(at: sourceIndex.row)

此外,当我尝试插入对象时,它会添加不止一次。

请帮忙。

使用以下代码,我希望它可以工作:-

self.pages[indexPath.section].questionItems.removeAll(keepingCapacity: false)
self.pages[indexPath.section].questionItems.append(questions)

从数组中删除对象:

var array = ["First Object", "Second Object", "Third Object"]
if let index = array.index(of:"Third Object") 
{
    array.remove(at: index)
}

我已经尝试过您的方案,它工作正常。我创建了一个模态命名页面,其中包含数组变量作为问题。并按下面给出的值填充值。

class Page {
    var questions = [String]();
}

填充样本值。

    let page1 = Page();
    page1.questions.append("P1->First Element");
    page1.questions.append("P1->Second Element");
    page1.questions.append("P1->Third Element");
    page1.questions.append("P1->Fourth Element");
    page1.questions.append("P1->Fifth Element");
    let page2 = Page();
    page2.questions.append("P2->First Element");
    page2.questions.append("P2->Second Element");
    page2.questions.append("P2->Third Element");
    page2.questions.append("P2->Fourth Element");
    let page3 =  Page();
    page3.questions.append("P3->First Element");
    page3.questions.append("P3->Second Element");
    page3.questions.append("P3->Thirs Element");

    var pages = [Page]();        
    pages.append(page1);
    pages.append(page2);
    pages.append(page3);

现在我们将在删除项目之前和删除项目之后看到输出。

    print("p1.question (pages[0].questions)");
    print("p2.question (pages[1].questions)");
    print("p3.question (pages[2].questions)");
    pages[1].questions.remove(at: 2);
    print("p1.question (pages[0].questions)");
    print("p2.question (pages[1].questions)");
    print("p3.question (pages[2].questions)");

现在,您可以按预期查看输出。

p1.question ["P1->First Element", "P1->Second Element", "P1->Third Element", "P1->Fourth Element", "P1->Fifth Element"]
p2.question ["P2->First Element", "P2->Second Element", "P2->Third Element", "P2->Fourth Element"]
p3.question ["P3->First Element", "P3->Second Element", "P3->Thirs Element"]
p1.question ["P1->First Element", "P1->Second Element", "P1->Third Element", "P1->Fourth Element", "P1->Fifth Element"]
p2.question ["P2->First Element", "P2->Second Element", "P2->Fourth Element"]
p3.question ["P3->First Element", "P3->Second Element", "P3->Thirs Element"]

如您所见,索引 1 页面中的第三个项目已成功删除。我认为您在letvar之间混淆了.在 swift 中,let 是不可变的对象,其中 var 是可变的对象。

最新更新