Search code examples
arraysswift3custom-typeequatable

How to create extension with Equatable to delete custom array element?


I have created custom array type. Now I want to have one more method in it, which can remove the element of the array by passing the actual element as an argument. I know this can be achieved if we add the extension of the custom array as Equitable.

Below is my code of proxy array:

struct ArrayProxy<T> {
 var array: [T] = []

 mutating func append(newElement: T) {
    self.array.append(newElement)

    print("Element added in download queue")
    DownloadContent.downloadChaptersFromDownloadQueue()
 }

 mutating func removeAtIndex(index: Int) {
    print("Removed object \(self.array[index]) at index \(index)")
    self.array.remove(at: index)
 }

 subscript(index: Int) -> T {
    set {
        print("Set object from \(self.array[index]) to \(newValue) at index \(index)")
        self.array[index] = newValue
    }
    get {
        return self.array[index]
    }
  }
}

below is my extension of the proxy array

extension ArrayProxy where T: Equatable {
    mutating func removeElement(element: T) {
    self.removeAtIndex(index: self.array.index(of: element)!)
 }
}

Solution

  • Force unwrap an optional value may cause an error.

    If index exist index(of:) only return first match index.

    fix:

    extension ArrayProxy where T: Equatable {
    
        mutating func removeElement(_ element: T) {
            var indexs: [Int] = []
            for (index, foo) in array.enumerated() {
                if foo == element {
                    indexs.append(index)
                }
            }
            indexs.sorted(by: >).forEach({
                array.remove(at: $0)
            })
        }
    }