如何基于id从swift上的对象数组中删除元素?

时间:2018-03-01 04:33:25

标签: arrays swift

我有一些对象,例如。

var arrStudents = [S1,S2,S3,S4,S5]

这里s1是学生班的对象

class Student {

    var id:Int!
    var name:String!
    var address:String?
    var phone:Int!
}

现在我想通过学生ID删除数组中的记录。请告诉我怎么做。

此外,我想学习使用filter,map的所有数组操作。

3 个答案:

答案 0 :(得分:1)

First Veriables名称应为小写。

只需使用属性 onChangeDropdown = e => { console.log(e.target.value); this.props.callbackFn(e.target.value); }; 搜索数组中搜索元素的索引,然后将其从学生数组中删除。

id

要了解以下示例:

  1. Higher order functions in swift: Filter, Map, Reduce, flatmap
  2. Simple Higher Order Functions in Swift 3.0 — Map, filter, reduce and flatMap!
  3. Swift Guide to Map Filter Reduce

答案 1 :(得分:0)

循环遍历数组的所有索引,并检查要删除的id是否匹配,如果是,它将过滤掉,你可以删除该索引: - )

let idToDelete = 10
if let index = arrStudents.index(where: {$0.id == idToDelete}) {
    array.remove(at: index)
}

如果要在单次迭代中删除多个值,则应该从最后一个索引到第一个索引启动循环,这样它就不会崩溃(超出绑定错误)

var idsToDelete = [10, 20]
for id in idsToDelete {
        for (i,str) in arrStudents.enumerated().reversed()
        {
            if str.id == id
            {
                arrStudents.remove(at: i)
            }
        }
    }

答案 2 :(得分:0)

struct Stu {
        let id: Int
        let name: String
    }

    let stu1 = Stu(id: 1, name: "Tom")
    let stu2 = Stu(id: 2, name: "Jhon")

    var arrString: [Stu] = [stu1, stu2]

    //filter will give you an array with the matched value
    let matchedObjectFromArray = arrString.filter { (obj) -> Bool in
        return obj.id == 1 //return Stu object whose id = 1
    }

    //index method gives index of object if found in an array otherwise gives nil
    if let indexOfObject = arrString.index(where: { (obj) -> Bool in
        return obj.id == 2 // return index of Stu object whose id = 2
    }) {

        let removedObject = arrString.remove(at: indexOfObject)
        print(removedObject.id)
    }