1

I've been struggling to implement this piece of code. I'm converting some legacy code over to swift and I can't get the equivalent of [annotation isKindofClass] to work.

Originally I went with something like (gave me errors

mapView.annotations.forEach {
        if !$0.isKind(of: MKUserLocation) {
            self.mapView.removeAnnotation($0)
        }
    }

But I read on this post that swift had a different way of doing it.

mapView.annotations.forEach {
        if !$0 is MKUserLocation {
            self.mapView.removeAnnotation($0)
        }
    }

this one gives me the error: Cannot convert value of type MKAnnotation to expected argument type BOOL

teachMeSenpai
  • 226
  • 1
  • 10

2 Answers2

2
public func isKind(of aClass: AnyClass) -> Bool

This function requires AnyClass as argument, you must pass a class, using .self

    mapView.annotations.forEach {
        if !$0.isKind(of: MKUserLocation.self) {
            self.mapView.removeAnnotation($0)
        }
    }

When use is, you must wrap the expression with parentheses:

    mapView.annotations.forEach {
        if !($0 is MKUserLocation) {
            self.mapView.removeAnnotation($0)
        }
    }

You are checking boolean value of $0, not the is expression, hence the error.

kientux
  • 1,782
  • 1
  • 17
  • 32
1

In short you can do With

mapView.annotations.remove(where:{ !($0 is MKUserLocation) } )
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87