Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift generic remove class instance from array

Tags:

swift

swift3

I want to achieve the following; being able to remove any given instance from an array. However the following is not valid Swift 3 syntax:

extension Array where Element: class { // error: Expected identifier for type name
    mutating func remove(_ object: AnyObject) {
        if let index = index(where: { $0 === object }) {
            remove(at: index)
        }
    }
}

protocol MyProtocol: class { }
class MyClass: MyProtocol { }
var myInstance = MyClass()
var myArray: [MyProtocol] = [myInstance]
myArray.remove(myInstance)

How would a generic approach work? I don't want to special-case the generic extension to MyProtocol or Equatable.

like image 466
Bouke Avatar asked Sep 07 '25 09:09

Bouke


1 Answers

Convert your restriction to AnyObject instead of class:

extension Array where Element: AnyObject {
    mutating func remove(_ object: Element) {
        if let index = firstIndex(where: { $0 === object }) {
            remove(at: index)
        }
    }
}

The below notes are no longer true, keeping them for historical purposes.

The only problem now is that the compiler won't let you declare var myArray: [MyProtocol], as it will throw the following:

error: using 'MyProtocol' as a concrete type conforming to protocol 'AnyObject' is not supported

So you'll need to var myArray: [AnyObject]. Here is a good explanation of why this restriction currently exists in Swift.

like image 55
Cristik Avatar answered Sep 10 '25 04:09

Cristik