在回答关于SO的另一个问题时,我发现CLLocation
类符合Equatable
协议。它用什么方法来确定平等?
lat / long的完全匹配?纬度/长度和高度的精确匹配?纬度,经度,海拔高度和时间戳的完全匹配?速度和路线怎么样?那些仅用纬度/长度对创建的CLLocation
个对象怎么样?该位置的各种其他值不是选项,那么使用init(latitude:longitude:)
创建的位置的高度是多少?
答案 0 :(得分:1)
CLLocation
如何实现Equatable协议?
它没有。没有重写的==
函数可以比较两个CLLocation
个实例。在使用两个==
个实例调用CLLocation
时,会使用NSObject
==
函数:
public func ==(lhs: NSObject, rhs: NSObject) -> Bool
要实际比较两个CLLocation
个实例,请比较您关注的每个实例(纬度或经度)的属性,或者将内置的distance(from:)
方法与两个位置一起使用,并将其与{{ 1}}门槛。
答案 1 :(得分:0)
CLLocation类与任何符合Equatable的类非常相似,实现了(==)运算符
为了回答你的其他问题,我决定用这段代码开始游乐场
import UIKit
import CoreLocation
var str = "Hello, playground"
var coordinate = CLLocationCoordinate2D.init(latitude: 42.0, longitude: 42.0)
var accuracy = CLLocationAccuracy.init(24.0)
var date = Date.init(timeIntervalSinceNow: 0)
var loc1 = CLLocation.init(coordinate: coordinate, altitude: 44.0, horizontalAccuracy: accuracy, verticalAccuracy: accuracy, timestamp: date)
var loc2 = CLLocation.init(coordinate: coordinate, altitude: 44.0, horizontalAccuracy: accuracy, verticalAccuracy: accuracy, timestamp: date)
var loc3 = CLLocation.init(latitude: 42.0, longitude: 42.0)
var loc4 = CLLocation.init(latitude: 42.0, longitude: 42.0)
var loc5 = CLLocation.init(coordinate: coordinate, altitude: 44.0, horizontalAccuracy: accuracy, verticalAccuracy: accuracy, course: .infinity, speed: 55.0, timestamp: date)
var loc6 = CLLocation.init(coordinate: coordinate, altitude: 44.0, horizontalAccuracy: accuracy, verticalAccuracy: accuracy, course: .infinity, speed: 55.0, timestamp: date)
var bool1 = loc1 == loc2 //false
var bool2 = loc2 == loc3 //false
var bool3 = loc2 == loc2 //true
var bool4 = loc1 == loc4 //false
var bool5 = loc5 == loc6 //false
并且唯一产生TRUE的bool是bool3。
因此,无论不同CLLocation对象上的各个属性是否相同,==运算符都不会将对象视为相等。我猜测比较位置的最佳方法是比较你感兴趣的CLLocation对象的字段
答案 2 :(得分:0)
我完全验证了JAL在答案中所说的内容,我写道:
import Foundation
import UIKit
import CoreLocation
class ViewController: UIViewController{
var cl1 = CLLocation()
var cl2 = CLLocation()
override func viewDidLoad() {
super.viewDidLoad()
if cl1 == cl2{
}
}
}
然后我命令点击了==
(来自if cl1 == cl2
)。它花了我:
extension NSObject : CVarArg {
}
public func ==(lhs: Selector, rhs: Selector) -> Bool
public func ==(lhs: NSObject, rhs: NSObject) -> Bool
public struct NSZone {
}
要仔细检查我的命令,点击了CLLocation
并看到:
open class CLLocation : NSObject, NSCopying, NSSecureCoding {
...
}
基本上==
是因为它是NSObject
的子类,只比较引用。