removeAtIndex()不适用于Swift数组

时间:2014-12-17 00:44:48

标签: ios arrays swift

我有一个Swift n00b问题。 我很难理解为什么我无法从数组中删除元素。

我首先过滤两次以仅包含我需要的值:

let filteredShowtimes = movieShowtimes.filter{$0.dateTime.laterDate(newStartTime!).isEqualToDate($0.dateTime)}
var furtherFilteredShowtimes = filteredShowtimes.filter{$0.endTime.earlierDate(endTime!).isEqualToDate($0.endTime)}

而且,在线下,在一个依赖于数组大小的while循环内 - 但不会迭代它或修改它 - 我尝试删除第一个元素,如下所示:

furtherFilteredShowtimes.removeAtIndex(0)

但元素数量保持不变。

知道我错过了什么吗?

这里是整个代码:

while(furtherFilteredShowtimes.count > 0) {
   println("showtime \(furtherFilteredShowtimes.first!.dateTime)")
      //if the start time of the movie is after the start of the time period, and its end before
      //the requested end time
      if (newStartTime!.compare(furtherFilteredShowtimes.first!.dateTime) == NSComparisonResult.OrderedAscending) && (endTime!.compare(furtherFilteredShowtimes.first!.endTime) == NSComparisonResult.OrderedDescending) {
          let interval = 1200 as NSTimeInterval
          //if the matching screenings dict already contains one movie,
          //make sure the next one starts within 20 min of the previous
          //one
          if(theaterMovies.count > 1 && endTime!.timeIntervalSinceDate(newStartTime!) < interval {
              //add movie to the matching screenings dictionary
              println("we have a match with \(movies[currentMovie.row].title)")
              theaterMovies[furtherFilteredShowtimes.first!.dateTime] = movies[currentMovie.row].title
              //set the new start time for after the added movie ends
              newStartTime = movieShowtimes.first!.endTime
              //stop looking for screenings for this movie
              break
          }
          else if(theaterMovies.count == 0) {
             //add movie to the matching screenings dictionary
             theaterMovies[furtherFilteredShowtimes.first!.dateTime] = movies[currentMovie.row].title
             println("we have a new itinerary with \(movies[currentMovie.row].title)")
             //set the new start time for after the added movie ends
             newStartTime = furtherFilteredShowtimes.first!.endTime
             //stop looking for screenings for this movie
             break
         }
     }
     else { //if the showtime doesn't fit, remove it from the list
         println("removing showtime \(furtherFilteredShowtimes.first!.dateTime)")
         furtherFilteredShowtimes.removeAtIndex(0)
     }

}

1 个答案:

答案 0 :(得分:0)

您只能在一个地方removeAtIndex(0)中说else

因此,如果它没有发生,那意味着永远不会执行该行,因为else未执行 - 而是执行if

并且break位于每个if的末尾,以便while循环结束!

换句话说,让我们假装前两个嵌套if条件成功。你的结构是这样的:

while(furtherFilteredShowtimes.count > 0) {
    if (something) {
        if (somethingelse) {
            break

break表示跳出while,所以如果这两个if条件成功,那就结束了!我们从不循环。我们当然永远不会进入removeAtIndex()