Swift에서 열거하는 동안 배열에서 제거 하시겠습니까?
Swift의 배열을 통해 열거하고 특정 항목을 제거하고 싶습니다. 이것이 안전한지, 그렇지 않다면 어떻게해야할지 궁금합니다.
현재 나는 이것을하고있다 :
for (index, aString: String) in enumerate(array) {
//Some of the strings...
array.removeAtIndex(index)
}
Swift 2에서는 enumerate
및 reverse
.
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)
이 새로운 방법에는 몇 가지 장점이 있습니다.
- .NET을 사용한 구현보다 빠릅니다
filter
. - 역전 어레이가 필요하지 않습니다.
- 제자리에서 항목을 제거하므로 새 배열을 할당하고 반환하는 대신 원래 배열을 업데이트합니다.
특정 인덱스의 요소가 배열에서 제거되면 한 위치 뒤로 이동하기 때문에 모든 후속 요소의 위치 (및 인덱스)가 변경됩니다.
따라서 가장 좋은 방법은 배열을 역순으로 탐색하는 것입니다.이 경우 기존 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
'code' 카테고리의 다른 글
HTML5 캔버스에서 흐릿한 텍스트를 수정하려면 어떻게해야합니까? (0) | 2020.10.16 |
---|---|
다중 인덱스 판다에서 선택 (0) | 2020.10.16 |
Visual Studio에서 프로젝트 네임 스페이스 변경 (0) | 2020.10.16 |
Bluetooth 장치가 연결되어 있는지 프로그래밍 방식으로 확인하는 방법은 무엇입니까? (0) | 2020.10.16 |
자바 스크립트의 요구 사항으로 임의의 암호 문자열 생성 (0) | 2020.10.15 |