Trouble understanding how to get index from 'annotation as! Location'

This requires a slightly longer explanation. Basically, in order for array elements to be compared, they have to adhere to the Equatable protocol. You can see details about it here:

And as part of the protocol, you have to define an == operator which defines how objects are compared against each other to determine if they are equal. So it is not quite as simple as simply taking a universal ID from each object and saying does the ID match. That’s what I was trying to explain.

In the particular instance of comparing two Location objects, the Location class is also extending NSManagedObject and so will conform to NSManagedObject’s Equatable implementation to compare the objects. Here, it probably does use the unique ID provided for the object, but that’s true only for this particular instance due to Location being a sub-class of NSManagedObject. For another class the comparison of the two objects could rely on a totally different property.

Swift does not use pointers for object comparison - this is what Objective-C did if I recall correctly. Swift actually compares values so that even two copies of the same object (with the same values) would compare as equal. Pointer comparison does not do this.

As I said in the previous response to @soxapps, please look up the documentation for the Equatable protocol.

Please re-read my post regarding this (the one above yours) which explains this covering the case for using a force unwrap vs. an optional unwrap …

Note that I did post this:

Presumably because of how things are arranged in the code, iOS will always assign a Location object to the annotation variable, so you can safely use the ! without fear that your app will crash.

I’m afraid that that’s slightly incorrect :slight_smile: What you see after the variable is the memory location of the variable - not its ID.

You seem to be implying that objects in Swift have an ID property? Is that the case?

Not sure where you got that implication from me :slight_smile: No, objects in Swift do not have a unique ID assigned to them by Swift itself. If you have an ID property (or an equivalent property which can act as a unique identifier) you can use it when comparing the one instance of the object to another. But that would be totally up to you.

In the case of the Location object it does get a unique ID but that is not assigned by Swift itself but because Location is derived from NSManagedObject and NSManagedObject, as a CoreData model object, does have a unique identifier.

thank you for the link

I read it and the MKAnnotation page Apple Developer Documentation

it seems that only the - Position Attributes var coordinate: CLLocationCoordinate2D

is compared based on equatable conformation

This topic was automatically closed after 166 days. New replies are no longer allowed.