如何安全地从for循环中的数组中删除项目? [英] How do I safely remove items from an array in a for loop?

查看:141
本文介绍了如何安全地从for循环中的数组中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部披露,这是一个作业问题:

Full disclose, this is for a homework question:

它应该具有[Circle]类型的私有属性.一组圆. 该方法应删除半径大于 最低要求,并且小于最高要求.

It should have a private property of type [Circle]. An array of circles. The method should remove any circles that have a radius larger than the minimum requirement, and smaller than the max requirement.

很明显,我应该使用removeAtIndex()删除不满足循环中确定条件的数组项.但是,由于我猜测是迭代器/索引不匹配",因此许多人指出了删除循环中项目的危险.

It seems obvious that I should use removeAtIndex() to remove array items that don't meet a condition determined in the loop. However, many have pointed out before the perils of removing items in a loop because of what I guess is a "iterator/index mismatch".

最终我最终创建了一个空数组,并使用.append()将满足良好"条件的值推送到filteredCircles数组,但我忍不住感觉到这不符合要求分配标准.

Ultimately I ended up creating an empty array and using .append() to push the values that meet the "good" condition to a filteredCircles array, but I can't help but to feel that this this doesn't meet the criteria for the assignment.

有没有一种解决方案可以真正从循环中删除数组中的项?

Is there a solution that actually removes the items from the array in a loop?

推荐答案

如果FOR LOOP强制性的(并且我在引文中没有看到此要求),则应使用filter方法.

If the FOR LOOP is not mandatory (and I don't see this requirement in the quoted text) you should use the filter method.

在数组上调用filter时,会得到一个新数组,其中仅包含确实符合传递给filter的闭包的值. 原始数组未突变.

When you invoke filter on an array you get a new array containing only the values that do respect the closure you passed to filter. The original array is not mutated.

struct Circle {
    let radius: Double
}

let circles = [Circle(radius: 1), Circle(radius: 5.1), Circle(radius: 4), Circle(radius: 10.8)]

let bigCircles = circles.filter { $0.radius > 5 }

为什么这种方法比在FOR LOOP中修改数组更好

  1. 由于circles是常量,因此您没有与多线程编程相关的问题.如果circles是可变的,那么当您循环它时,其他线程可能会对其进行更改,从而产生非常可怕的副作用.
  2. 不易出错.您不是在编写CPU应该做什么,而是在描述结果的样子.这样,您和编译器之间的潜在误会就更少了:)
  3. 您正在编写更少的代码,这意味着更少的潜在错误.
  1. Since circles is a constant, you don't have problems related to multithreading programming. If circles was mutable then other threads could change it while you are looping it with very scary side effects.
  2. It's less error prone. You are not writing what the CPU should do, instead you are describing how the results should be. So less potential misunderstandings between you and the compiler :)
  3. You are writing less code which does mean less potential mistakes.

这些是编写函数式编程代码的一些好处.

These are some of the benefits of writing Functional Programming code.

这篇关于如何安全地从for循环中的数组中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆