ios Swift:删除所有数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31183431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: delete all array elements
提问by Mehmet
I am trying to delete all array elements with a for loop like this:
我正在尝试使用这样的 for 循环删除所有数组元素:
for index 1...myArray.count {
myArray.removeAtIndex(index)
}
But it doesn't work, I get this error before bulding:
但它不起作用,我在构建之前收到此错误:
Expected ';' in 'for' statement
预期的 ';' 在'for'语句中
回答by vadian
There is a method (actually a function)
有一个方法(实际上是一个函数)
myArray.removeAll()
回答by Antonio
Taking for granted that @vadian's answer is the solution, I would just want to point out that your code doesn't work.
理所当然地认为@vadian 的答案是解决方案,我只想指出您的代码不起作用。
First of all, array indexes are 0-based, so you should rewrite the range accordingly:
首先,数组索引是从 0 开始的,因此您应该相应地重写范围:
for index 0..<myArray.count {
myArray.removeAtIndex(index)
}
However this implementation is going to cause a crash. If you have an array of 10 elements, the last element occupies the position at index 9.
但是,此实现将导致崩溃。如果您有一个包含 10 个元素的数组,则最后一个元素占据索引 9 处的位置。
Using that loop, at the first iteration the element at index 0 is removed, and that causes the last element to shift down at index 8.
使用该循环,在第一次迭代时,索引 0 处的元素被删除,这导致最后一个元素在索引 8 处向下移动。
At the next iteration, the element at index 1 is removed, and the last element shifts down at index 7. And so on.
在下一次迭代中,索引 1 处的元素被移除,最后一个元素在索引 7 处向下移动。依此类推。
At some point in the loop, an attempt to remove an element for a non existing index will cause the app to crash.
在循环中的某个时刻,尝试删除不存在索引的元素将导致应用程序崩溃。
When removing elements from an array in a loop, the best way of doing it is by traversing it in reverse order:
在循环中从数组中删除元素时,最好的方法是以相反的顺序遍历它:
for index in reverse(0..<myArray.count) {
myArray.removeAtIndex(index)
}
That ensures that removed elements don't change the order or the index of the elements still to be processed.
这确保了被移除的元素不会改变仍要处理的元素的顺序或索引。
回答by V.J.
If you really want to clear the array, the simplest way is to Re-Initialize it.
如果你真的想清空数组,最简单的方法就是重新初始化它。
回答by Kyle Decot
You're missing the in
keyword which is causing your error. The code should be:
您缺少in
导致错误的关键字。代码应该是:
for index in 1...myArray.count {
myArray.removeAtIndex(index)
}
This will however not work as you would expect for a couple of reasons:
但是,由于以下几个原因,这不会像您期望的那样工作:
- The last valid index is
count - 1
which would require1..<myArray.count
- More importantly removing an element from an array shortens it thus changing the indexes each time.
- 最后一个有效索引是
count - 1
需要1..<myArray.count
- 更重要的是,从数组中删除一个元素会缩短它,从而每次都更改索引。
If you're trying to remove all things from the array then you should do as others have suggested and use:
如果您试图从数组中删除所有内容,那么您应该按照其他人的建议进行操作并使用:
myArray.removeAll()
In the case that you do only want the first element and nothing else you could get a reference to the first object, empty the array, then add the object back on:
如果您只想要第一个元素而没有其他任何东西,您可以获得对第一个对象的引用,清空数组,然后重新添加对象:
var firstElement = myArray.first!
myArray.removeAll()
myArray.append(firstElement)
回答by Lorem Ipsum Dolor
Your code should work, it is just out of bound.
您的代码应该可以工作,只是越界了。
Swift 3
斯威夫特 3
existingArray = []
By doing this you re-assign an empty array to the existing array and the data type is referred.
通过这样做,您将一个空数组重新分配给现有数组并引用数据类型。
Alternatively, you can use removeAll
which removes all elements from the array and provide an option to keep the existing capacity.
或者,您可以使用removeAll
which 从数组中删除所有元素并提供一个选项来保留现有容量。
existingArray.removeAll()
This is a mutating
function which means the array calling the method will be changed (empty).
这是一个mutating
函数,这意味着调用该方法的数组将被更改(空)。
回答by vikingosegundo
Kyle is on the right track, but his code will fail as the possible indices reduces during enumerating, leading to illegal indices.
Kyle 是在正确的轨道上,但他的代码将失败,因为在枚举期间可能的索引减少,导致非法索引。
One way to solve it is to enumerate backwards. In swift this is done by using strides.
解决它的一种方法是向后枚举。在 swift 中,这是通过使用strides来完成的。
for index in stride(from: myArray.count - 1, through: 0, by: -1) {
myArray.removeAtIndex(index)
}
another options would be to use filter()
另一种选择是使用 filter()
Swift 1.2
斯威夫特 1.2
myArray = filter(myArray, { (obj) -> Bool in
return false
})
Swift 2
斯威夫特 2
myArray = myArray.filter{ (obj) -> Bool in
return false
}
回答by Jayprakash Dubey
There is removeAllObjects()method available in Swift 2
有removeAllObjects()中夫特2可用的方法
Syntax : public func removeAllObjects()
Eg.: mainArray.removeAllObjects
To remove element at particular index use :
要删除特定索引处的元素,请使用:
Syntax : public func removeObjectAtIndex(index: Int)
Eg.: mainArray.removeObjectAtIndex(5)
To remove last element use :
要删除最后一个元素,请使用:
Syntax : public func removeLastObject()
Eg.: mainArray.removeLastObject()
To remove elements in particular range use :
要删除特定范围内的元素,请使用:
Syntax : public func removeObject(anObject: AnyObject, inRange range: NSRange)
To remove particular element use :
要删除特定元素,请使用:
Syntax : public func removeObject(anObject: AnyObject)
Below screenshot shows list of method available in NSMutableArray extension
下面的屏幕截图显示了 NSMutableArray 扩展中可用的方法列表
回答by Darth Flyeater
You can also do this:
你也可以这样做:
for _ in myArray
{
myArray.removeAtIndex(0)
}
回答by Josh Hrach
Vadian has the correct answer in terms of what you're trying to accomplish. The issue shown as a result of your code sample is due to the way you're trying to create the for
loop. Index
will start at 0 by default. Adding in a number range after it is not the correct way to create a for loop. That's why you're seeing the error. Instead, create your for loop as follows:
就您要完成的工作而言,Vadian 有正确的答案。由于您的代码示例而显示的问题是由于您尝试创建for
循环的方式造成的。Index
默认从 0 开始。在它之后添加一个数字范围不是创建 for 循环的正确方法。这就是您看到错误的原因。相反,按如下方式创建您的 for 循环:
for index in myArray.indices {
// Do stuff
}
Hopefully, this answer will help others that are new to Swift or programming.
希望这个答案能帮助其他不熟悉 Swift 或编程的人。
回答by PatelFab
For removing all the data from an array
用于从数组中删除所有数据
yourArrayData.removeAll()
yourArrayData.removeAll()