programing tip

Swift : 모든 배열 요소 삭제

itbloger 2020. 8. 26. 07:37
반응형

Swift : 모든 배열 요소 삭제


다음과 같이 for 루프를 사용하여 모든 배열 요소를 삭제하려고합니다.

for index 1...myArray.count {
   myArray.removeAtIndex(index)
}

하지만 작동하지 않습니다. bulding 전에이 오류가 발생합니다.

';'가 필요합니다. 'for'문에서


방법이 있습니다 (실제로는 기능)

myArray.removeAll()

@vadian의 대답 이 해결책 이라는 것을 당연하게 생각하면 코드가 작동하지 않는다는 점을 지적하고 싶습니다.

우선 배열 인덱스는 0부터 시작하므로 그에 따라 범위를 다시 작성해야합니다.

for index 0..<myArray.count {
   myArray.removeAtIndex(index)
}

그러나이 구현은 충돌을 일으킬 것입니다. 10 개 요소의 배열이있는 경우 마지막 요소는 인덱스 9의 위치를 ​​차지합니다.

이 루프를 사용하면 첫 번째 반복에서 인덱스 0의 요소가 제거되고 마지막 요소가 인덱스 8에서 아래로 이동합니다.

다음 반복에서 인덱스 1의 요소가 제거되고 마지막 요소는 인덱스 7에서 아래로 이동합니다.

루프의 어느 시점에서 존재하지 않는 인덱스에 대한 요소를 제거하려고하면 앱이 중단됩니다.

루프의 배열에서 요소를 제거 할 때 가장 좋은 방법은 역순으로 순회하는 것입니다.

for index in reverse(0..<myArray.count) {
    myArray.removeAtIndex(index)
}

이렇게하면 제거 된 요소가 처리 될 요소의 순서 나 색인이 변경되지 않습니다.


in오류를 일으키는 키워드 가 없습니다 . 코드는 다음과 같아야합니다.

for index in 1...myArray.count {
    myArray.removeAtIndex(index)
}

그러나 다음과 같은 몇 가지 이유로 예상대로 작동하지 않습니다.

  • 마지막으로 유효한 지수는 count - 1요구되는1..<myArray.count
  • 더 중요한 것은 배열에서 요소를 제거하면 길이가 줄어들어 매번 인덱스가 변경됩니다.

배열에서 모든 것을 제거하려는 경우 다른 사람들이 제안하고 사용하는대로 수행해야합니다.

myArray.removeAll()

첫 번째 요소 만 원하고 다른 요소는 필요하지 않은 경우 첫 번째 개체에 대한 참조를 얻을 수 있고 배열을 비운 다음 개체를 다시 추가 할 수 있습니다.

var firstElement = myArray.first!
myArray.removeAll()
myArray.append(firstElement)

정말로 어레이를 지우고 싶다면 가장 간단한 방법은 다시 초기화하는 것입니다.


코드가 작동해야하며 범위를 벗어났습니다.

스위프트 3

existingArray = []

이렇게하면 기존 배열에 빈 배열을 다시 할당하고 데이터 유형이 참조됩니다.

또는 removeAll어레이에서 모든 요소를 ​​제거하고 기존 용량을 유지하는 옵션을 제공하는 방법을 사용할 수 있습니다.

existingArray.removeAll()

mutating메서드를 호출하는 배열이 변경 (비어 있음)을 의미 하는 함수입니다.


Kyle is on the right track, but his code will fail as the possible indices reduces during enumerating, leading to illegal indices.

One way to solve it is to enumerate backwards. In swift this is done by using strides.

for index in stride(from: myArray.count - 1, through: 0, by: -1) {
    myArray.removeAtIndex(index)
}

another options would be to use filter()

Swift 1.2

myArray = filter(myArray, { (obj) -> Bool in
    return false
})

Swift 2

myArray = myArray.filter{ (obj) -> Bool in
    return false
}

There is removeAllObjects() method available in Swift 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

Screenshot 1


You can also do this:

for _ in myArray
{
    myArray.removeAtIndex(0)
}

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:

for index in myArray.count {
    // Do stuff
}

Hopefully, this answer will help others that are new to Swift or programming.

참고URL : https://stackoverflow.com/questions/31183431/swift-delete-all-array-elements

반응형