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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With