Search code examples
swiftswiftuicllocationhashable

How to add the Hashable protocol to CLLocationCoordinate2D using an extension in SwiftUI


So I have a custom struct with one property of type String and another of type CLLocationCoordinate2D. Apparently, String conforms to Hashable and if I can extend CLLocationCoordinate2D to conform to Hashable, my custom struct will also be Hashable. Here's my attempt at extending CLLocationCoordinate2D:

extension CLLocationCoordinate2D {
    static func == (lhs: Self, rhs: Self) -> Bool {
        return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(self.latitude) //wasn't entirely sure what to put for the combine parameter but I saw similar things online
    }
}

Solution

  • You need to declare Hashable explicitly:

    extension CLLocationCoordinate2D: Hashable {
        public static func == (lhs: Self, rhs: Self) -> Bool {
            return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
        }
        
        public func hash(into hasher: inout Hasher) {
            hasher.combine(latitude)
            hasher.combine(longitude)
        }
    }