Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does CLLocation implement the Equatable protocol?

Tags:

In answering another question on SO, I found that the CLLocation class conforms to the Equatable protocol. What method does it use to determine equality?

Exact match of lat/long? Exact match of lat/long and altitude? Exact match of latitude, longitude, altitude, and timestamp? What about speed and course? What about CLLocation objects that were created with only a lat/long pair? Various other values of the location are not optionals, so what would the altitude be for a location created using init(latitude:longitude:)?

like image 286
Duncan C Avatar asked Sep 13 '17 22:09

Duncan C


2 Answers

Just fully verify what JAL has said in his answer, I wrote:

import Foundation
import UIKit
import CoreLocation

class ViewController: UIViewController{

    var cl1 = CLLocation()
    var cl2 = CLLocation()

    override func viewDidLoad() {
        super.viewDidLoad()
        if cl1 == cl2{

        }
    }
}

Then I command clicked on the == (from if cl1 == cl2). It took me to:

extension NSObject : CVarArg {
}

public func ==(lhs: Selector, rhs: Selector) -> Bool

public func ==(lhs: NSObject, rhs: NSObject) -> Bool

public struct NSZone {
}

To double check I command clicked on CLLocation and saw:

open class CLLocation : NSObject, NSCopying, NSSecureCoding {
...
}

So basically the == is because it's subclassed from NSObject which only compares references.

like image 71
mfaani Avatar answered Sep 23 '22 11:09

mfaani


How does CLLocation implement the Equatable protocol?

It doesn't. There is no overridden == function which compares two CLLocation instances. When calling == with two CLLocation instances, the NSObject == function is used:

public func ==(lhs: NSObject, rhs: NSObject) -> Bool

To actually compare two CLLocation instances, either compare the properties on each you care about (latitude or longitude), or use the built in distance(from:) method with two locations and compare that to a CLLocationDistance threshold.

like image 23
JAL Avatar answered Sep 21 '22 11:09

JAL