code

Swift에서 열거하는 동안 배열에서 제거 하시겠습니까?

codestyles 2020. 10. 16. 07:26
반응형

Swift에서 열거하는 동안 배열에서 제거 하시겠습니까?


Swift의 배열을 통해 열거하고 특정 항목을 제거하고 싶습니다. 이것이 안전한지, 그렇지 않다면 어떻게해야할지 궁금합니다.

현재 나는 이것을하고있다 :

for (index, aString: String) in enumerate(array) {
    //Some of the strings...
    array.removeAtIndex(index)
}

Swift 2에서는 enumeratereverse.

var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
    a.removeAtIndex(i)
}
print(a)

여기 내 swiftstub을 참조하십시오 : http://swiftstub.com/944024718/?v=beta


filter방법을 고려할 수 있습니다 .

var theStrings = ["foo", "bar", "zxy"]

// Filter only strings that begins with "b"
theStrings = theStrings.filter { $0.hasPrefix("b") }

의 매개 변수 filter는 배열 유형 인스턴스 (이 경우 String) 를 취하고 Bool. 결과가 true요소를 유지하면 요소가 필터링됩니다.


에서 스위프트 3, 4 ,이 될 것이다 :

Johnston의 답변에 따르면 숫자로 :

var a = [1,2,3,4,5,6]
for (i,num) in a.enumerated().reversed() {
   a.remove(at: i)
}
print(a)

OP의 질문으로 문자열 사용 :

var b = ["a", "b", "c", "d", "e", "f"]

for (i,str) in b.enumerated().reversed()
{
    if str == "c"
    {
        b.remove(at: i)
    }
}
print(b)

그러나 이제 Swift 4.2 이상 에서는 WWDC2018에서 Apple이 권장 한 더 좋고 빠른 방법 이 있습니다.

var c = ["a", "b", "c", "d", "e", "f"]
c.removeAll(where: {$0 == "c"})
print(c)

이 새로운 방법에는 몇 가지 장점이 있습니다.

  1. .NET을 사용한 구현보다 빠릅니다 filter.
  2. 역전 어레이가 필요하지 않습니다.
  3. 제자리에서 항목을 제거하므로 새 배열을 할당하고 반환하는 대신 원래 배열을 업데이트합니다.

특정 인덱스의 요소가 배열에서 제거되면 한 위치 뒤로 이동하기 때문에 모든 후속 요소의 위치 (및 인덱스)가 변경됩니다.

따라서 가장 좋은 방법은 배열을 역순으로 탐색하는 것입니다.이 경우 기존 for 루프를 사용하는 것이 좋습니다.

for var index = array.count - 1; index >= 0; --index {
    if condition {
        array.removeAtIndex(index)
    }
}

However in my opinion the best approach is by using the filter method, as described by @perlfly in his answer.


No it's not safe to mutate arrays during enumaration, your code will crash.

If you want to delete only a few objects you can use the filter function.


Either create a mutable array to store the items to be deleted and then, after the enumeration, remove those items from the original. Or, create a copy of the array (immutable), enumerate that and remove the objects (not by index) from the original while enumerating.


I recommend to set elements to nil during enumeration, and after completing remove all empty elements using arrays filter() method.

참고URL : https://stackoverflow.com/questions/28323848/removing-from-array-during-enumeration-in-swift

반응형