I want to check if I already have a delegate in my removeDelegate method before removing. How do I do that?
Here's what I've got so far:
protocol LocationManagerDelegate {
func locationManagerDidUpdateLocation(
oldLocation: CLLocationCoordinate2D,
currentLocation: CLLocationCoordinate2D
)
}
class LocationManager: NSObject {
private var _delegates = [LocationManagerDelegate]()
func removeDelegate(delegate:LocationManagerDelegate) {
if contains(_delegates, delegate) {
// Remove delegate
}
}
}
However, this gives me the following error on the 'if contains' line:
cannot invoke 'contains' with an argument list of type '(@lvalue Array< LocationManagerDelegate >!, LocationManagerDelegate)'
Update for Swift 3:
Assuming that the delegates are actually instances of a class, you could require that in the protocol by "inheriting" from "class":
and then use the
index(where:)
method, using the "indentitiy operator===
:Old answer (Swift 1):
There are two slightly different
contains()
functions:You are using the first one, which requires that the sequence elements conform to the
Equatable
protocol, i.e. they can be compared with==
.Assuming that the delegates are actually instances of a class, you could require that in the protocol by "inheriting" from "class":
and then use the second, predicate-based version of
contains()
with the identity operator===
:To remove the object from the array you'll have to get its index, so you might use the
findIdenticalObject()
function from https://stackoverflow.com/a/25543084/1187415:and then find and remove from the array with
The arguments to
contains
must implement the Equatable protocol since it is defined as:Since there's no way to indicate that
LocationManagerDelegate
implements Equatable, I don't think you can use it. The obvious attempt would be:But that will fail when you try to declare the array because Equatable uses Self.
The best option I can come up with is: