programing

Swift에서 배열에서 요소를 제거하는 방법

subpage 2023. 4. 9. 21:30
반응형

Swift에서 배열에서 요소를 제거하는 방법

Apple의 새로운 언어 Swift로 배열에서 요소를 설정 해제/삭제하려면 어떻게 해야 합니까?

다음은 코드입니다.

let animals = ["cats", "dogs", "chimps", "moose"]

요소가 animals[2](서양속담, 친구속담)

let키워드는 변경할 수 없는 상수를 선언하기 위한 것입니다.는 '변수 수정하다'를 해야 합니다.var예를 들어 다음과 같습니다.

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2)  //["cats", "dogs", "moose"]

원래 컬렉션을 변경하지 않는 대체 방법은 다음과 같습니다.filter하지 않고 새과 같이

let pets = animals.filter { $0 != "chimps" }

정해진

var animals = ["cats", "dogs", "chimps", "moose"]

첫 번째 요소 제거

animals.removeFirst() // "cats"
print(animals)        // ["dogs", "chimps", "moose"]

마지막 요소 제거

animals.removeLast() // "moose"
print(animals)       // ["cats", "dogs", "chimps"]

인덱스에서 요소 제거

animals.remove(at: 2) // "chimps"
print(animals)           // ["cats", "dogs", "moose"]

알 수 없는 인덱스의 요소 제거

1개의 요소에 대해서만

if let index = animals.firstIndex(of: "chimps") {
    animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]

여러 요소의 경우

var animals = ["cats", "dogs", "chimps", "moose", "chimps"]

animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]

메모들

Swift 5.2로 업데이트

위의 답변에서는 삭제할 요소의 인덱스를 알고 있다고 가정하고 있습니다.

어레이에서 삭제할 객체에 대한 참조를 알고 있는 경우가 많습니다(배열을 반복하여 검색했습니다).이 경우 인덱스를 어디에나 전달하지 않고도 개체 참조를 직접 작업하는 것이 더 쉬울 수 있습니다.그래서 저는 이 해결책을 제안합니다.ID 연산자를 사용합니다. !==2개의 오브젝트 참조가 모두 같은 오브젝트인스턴스를 참조하는지 여부를 테스트하기 위해 사용합니다.

func delete(element: String) {
    list = list.filter { $0 != element }
}

물론 이 방법이 꼭 필요한 것만 있는 것은 아닙니다.Strings.

Swift 5: 어레이 내의 요소를 필터링 없이 쉽게 제거할 수 있는 쿨하고 쉬운 확장 기능을 다음에 나타냅니다.

   extension Array where Element: Equatable {

    // Remove first collection element that is equal to the given `object`:
    mutating func remove(object: Element) {
        guard let index = firstIndex(of: object) else {return}
        remove(at: index)
    }

}

사용방법:

var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"

myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]

다른할 수 있습니다.IntElement유형입니다.

var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17

myArray.remove(object: objectToRemove) // [4, 8, 6, 2]

Swift4의 경우:

list = list.filter{$0 != "your Value"}

Xcode 10+와 WWDC 2018 세션 223 "Embracing Algorithms"에 따르면 앞으로 좋은 방법은mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows

Apple의 예:

var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]

phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."

Apple 문서 참조

OP의 예에서는 동물 제거[2], "chimps":

var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }

이 방법은 크기가 잘 조정되고(선형 대 2차) 가독성이 뛰어나며 깨끗하기 때문에 선호될 수 있습니다.Xcode 10+에서만 작동하며, 현재 이 기능은 베타 버전입니다.

사용자 지정 개체 배열이 있는 경우 다음과 같이 특정 속성별로 검색할 수 있습니다.

if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
    doctorsInArea.remove(at: index)
}

또는 예를 들어 이름으로 검색하려는 경우

if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
    doctorsInArea.remove(at: index)
}

그럴 수 있어요. ★★★★★★★★★★★★★★★★★★.Dog이치노★★★★★★★★★★★★★★★★★★★★★★★★★★★, 그럼 여기에다가 더해져요.for 하는 말Dog어레이에서 여러 번 발생할 수 있습니다.

var animals = ["Dog", "Cat", "Mouse", "Dog"]
let animalToRemove = "Dog"

for object in animals {
    if object == animalToRemove {
        animals.remove(at: animals.firstIndex(of: animalToRemove)!)
    }
}

Dog어레이에서 종료되어 한 번만 발생합니다.

animals.remove(at: animals.firstIndex(of: animalToRemove)!)

둘 다 있으면 문자열과 숫자

var array = [12, 23, "Dog", 78, 23]
let numberToRemove = 23
let animalToRemove = "Dog"

for object in array {

    if object is Int {
        // this will deal with integer. You can change to Float, Bool, etc...
        if object == numberToRemove {
        array.remove(at: array.firstIndex(of: numberToRemove)!)
        }
    }
    if object is String {
        // this will deal with strings
        if object == animalToRemove {
        array.remove(at: array.firstIndex(of: animalToRemove)!)
        }
    }
}

제거할 요소의 인덱스를 알 수 없고 요소가 Equatable 프로토콜을 준수하는 경우 다음을 수행할 수 있습니다.

animals.remove(at: animals.firstIndex(of: "dogs")!)

Equatable 프로토콜 답변 참조:indexOfObject 또는 적절한 containsObject를 수행하는 방법

Swift의 어레이와 관련된 작업은 거의 없습니다.

어레이 작성

var stringArray = ["One", "Two", "Three", "Four"]

어레이에 개체 추가

stringArray = stringArray + ["Five"]

인덱스 개체에서 값 가져오기

let x = stringArray[1]

오브젝트 추가

stringArray.append("At last position")

인덱스에 개체 삽입

stringArray.insert("Going", at: 1)

개체 제거

stringArray.remove(at: 3)

Concat 객체 값

var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"

인덱스 배열을 사용하여 요소 제거:

  1. 문자열 및 인덱스 배열

    let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
    let indexAnimals = [0, 3, 4]
    let arrayRemainingAnimals = animals
        .enumerated()
        .filter { !indexAnimals.contains($0.offset) }
        .map { $0.element }
    
    print(arrayRemainingAnimals)
    
    //result - ["dogs", "chimps", "cow"]
    
  2. 정수 및 인덱스 배열

    var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
    let indexesToRemove = [3, 5, 8, 12]
    
    numbers = numbers
        .enumerated()
        .filter { !indexesToRemove.contains($0.offset) }
        .map { $0.element }
    
    print(numbers)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    



다른 배열의 요소 값을 사용하여 요소 제거

  1. 정수 배열

    let arrayResult = numbers.filter { element in
        return !indexesToRemove.contains(element)
    }
    print(arrayResult)
    
    //result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
    
  2. 문자열 배열

    let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
    let arrayRemoveLetters = ["a", "e", "g", "h"]
    let arrayRemainingLetters = arrayLetters.filter {
        !arrayRemoveLetters.contains($0)
    }
    
    print(arrayRemainingLetters)
    
    //result - ["b", "c", "d", "f", "i"]
    

.★★★★★★★★★★★★★★★★★★★★★★★★★★,Array의 하여)ArrayEquatable:

extension Array where Element: Equatable {
  
  mutating func removeEqualItems(_ item: Element) {
    self = self.filter { (currentItem: Element) -> Bool in
      return currentItem != item
    }
  }

  mutating func removeFirstEqualItem(_ item: Element) {
    guard var currentItem = self.first else { return }
    var index = 0
    while currentItem != item {
      index += 1
      currentItem = self[index]
    }
    self.remove(at: index)
  }
  
}
  

사용방법:

var test1 = [1, 2, 1, 2]
test1.removeEqualItems(2) // [1, 1]

var test2 = [1, 2, 1, 2]
test2.removeFirstEqualItem(2) // [1, 1, 2]

@Suragch의 "알 수 없는 인덱스의 요소 제거"에 대한 대안:

오브젝트 자체 대신 술어에 일치하는 보다 강력한 버전의 "index Of(element)"가 있습니다.이름은 같지만 myObjects.indexOf{$0.property = valueToMatch}에 의해 호출되었습니다.myObjects 배열에서 발견된 첫 번째 일치 항목의 인덱스를 반환합니다.

요소가 객체/구조물인 경우 특성 중 하나의 값을 기준으로 해당 요소를 제거할 수 있습니다.예를 들어, car.color 속성을 가진 Car 클래스가 있는데 carsArray에서 "빨간색" 자동차를 제거하려고 합니다.

if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
  carsArray.removeAtIndex(validIndex)
}

예상대로 위의 if 문을 반복/while 루프 내에 삽입하고 else 블록을 추가하여 플래그를 루프에서 "브레이크"하도록 설정하면 이 작업을 다시 수행하여 "모든" 빨간색 차량을 제거할 수 있습니다.

스위프트 5

guard let index = orders.firstIndex(of: videoID) else { return }
orders.remove(at: index)

이것으로 충분합니다(테스트되지 않았습니다).

animals[2...3] = []

: you : 편 it it it it it 로 해야 합니다.var 이에요.let그렇지 않으면 불변의 상수입니다.

String 개체를 제거하는 확장

extension Array {
    mutating func delete(element: String) {
        self = self.filter() { $0 as! String != element }
    }
}

Varun과 거의 같은 확장자를 사용하지만, 이 확장자(아래)는 범용입니다.

 extension Array where Element: Equatable  {
        mutating func delete(element: Iterator.Element) {
                self = self.filter{$0 != element }
        }
    }

하려면 , 를 합니다.remove(at:),removeLast()그리고.removeAll().

yourArray = [1,2,3,4]

두 위치에서 값을 제거합니다.

yourArray.remove(at: 2)

배열에서 마지막 값 제거

yourArray.removeLast()

세트에서 모든 멤버를 제거합니다.

yourArray.removeAll()

언급URL : https://stackoverflow.com/questions/24051633/how-to-remove-an-element-from-an-array-in-swift

반응형