Swift 2字符串数组删除Spesific Index错误

时间:2018-07-24 10:57:35

标签: arrays swift string swift2

我有字符串数组;

var students                      = [String]()

和我的学生数组输出:

students[0]:102----3----
students[1]:102-2018.07.24-4--6---
students[2]:103--5--4--
students[3]:34-2018.07.24---3-4--6--
students[4]:34--6---5----4--

我想删除学生[0] ,以便与学生[0]和学生[0]相同的学生[1]没有日期。

我想删除学生[4] ,以便学生[3]与学生[4]和学生[4]的ID相同。

在Swift 2中,我该怎么做?

必须输出

students[0]:102-2018.07.24-4--6---
students[1]:103--5--4--
students[2]:34-2018.07.24---3-4--6--

我的测试代码;

var count = 0
for mystudents in self.students {                                      
    let explode1 = "\(mystudents)".componentsSeparatedByString("-")
    let explode2 = "\(mystudents)".componentsSeparatedByString("-")                                     

    if  (explode1[0] == explode2[0]) { // HERE if equal same ids                                       
        if (explode1[1] == "" || explode2[1] == ""]){                     
           self.students.removeAtIndex(count++) // HERE gives fatal error: Index out of range
        }                                        
    }                                      
}

我大约5天没有解决问题,谁会解决这个问题,我将在悬赏2天后给予 500次

1 个答案:

答案 0 :(得分:2)

我建议您采用以下解决方案,因为您希望删除仅具有id的对象,并且该对象与具有相同id和日期的其他对象匹配。如果我的理解是错误的,请告诉我

    let students = ["102----3----",
                    "103--5--4--",
                    "102-2018.07.24-4--6---",
                    "34-2018.07.24---3-4--6--",
                    "34--6---5----4--"]

    let filtered = students.filter { (student) -> Bool in
        let id = student.characters.split{$0 == "-"}.map({ String($0) })
        let exists = students.filter({ (other) -> Bool in
            if student == other {
                return false
            }
            let otherId = other.characters.split{$0 == "-"}.map({String($0) }).first!
            return id.first! == otherId
        }).first
        if exists != nil, id.count > 1 {
            return id[1].characters.filter({ $0 == "."}).count == 2
        }
        return true
    }
    print(filtered)

输出:

["103--5--4--", "102-2018.07.24-4--6---", "34-2018.07.24---3-4--6--"]