【问题标题】:Swift 2 String Array remove Spesific Index ErrorSwift 2 字符串数组删除特定索引错误
【发布时间】:2018-12-31 23:21:56
【问题描述】:

我有字符串数组;

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--

我想删除students[0],这样students[1]的id与students[0]相同,students[0]没有日期。

我想删除students[4],这样students[3] 的id 与student[4] 相同,students[4] 没有日期。

在 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 次重复 赏金

【问题讨论】:

  • 你想要什么最终结果?
  • 这和你之前的问题stackoverflow.com/q/50030577/1187415有关吗?还是您只是在寻找remove(at: index)
  • 我添加的必须输出问题底部
  • 我建议你使用 Swift 4 和谷歌什么是数据结构。
  • @RajuyourPepe 我在 swift 2 中的项目 :(

标签: arrays swift string swift2


【解决方案1】:

我建议以下解决方案,前提是您要删除仅具有 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--"]

【讨论】:

  • @Kamran 老兄这是动态数据,必须是如果有相同的 id 并且只删除日期为空的
  • @SwiftDeveloper 我更新了答案。可以看看吗?
  • @Kamran 我在看
  • @dude 2 行有拆分的给出:错误:“字符串”类型的值没有成员“拆分”
  • 我觉得你得把split改成componentsSeparatedByString("-")
猜你喜欢
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多