2016-08-14 2 views
16

Das Hashable Protokoll in Swift erfordert, dass Sie eine Eigenschaft implementieren hashValue genannt:Unterschied zwischen Swift Hash und HashValue

protocol Hashable : Equatable { 
    /// Returns the hash value. The hash value is not guaranteed to be stable 
    /// across different invocations of the same program. Do not persist the hash 
    /// value across program runs. 
    /// 
    /// The value of `hashValue` property must be consistent with the equality 
    /// comparison: if two values compare equal, they must have equal hash 
    /// values. 
    var hashValue: Int { get } 
} 

Aber es scheint, gibt es auch eine ähnliche Eigenschaft namens hash.

Was ist der Unterschied zwischen hash und hashValue?

+3

'hash' ist eine Eigenschaft des [' NSObject'-Protokolls] (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/), vergleiche [NSObject-Unterklasse in Swift: Hash vs HashValue, isEqual vs ==] (http://StackOverflow.com/questions/33319959/nsobject-subclass-in-swift-hash-vshashvalue-isequal-vs). –

Antwort

23

hash ist eine erforderliche Eigenschaft in der NSObject protocol, die Methoden gruppiert, die für alle Objective-C-Objekte grundlegend sind, so dass Swift älter ist. Die Standardimplementierung gibt nur die Objektadresse zurück, wie in NSObject.mm zu sehen ist, aber man kann die Eigenschaft in NSObject Unterklassen überschreiben.

hashValue ist eine erforderliche Eigenschaft des Swift Hashable Protokolls.

extension NSObject : Equatable, Hashable { 
    /// The hash value. 
    /// 
    /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` 
    /// 
    /// - Note: the hash value is not guaranteed to be stable across 
    /// different invocations of the same program. Do not persist the 
    /// hash value across program runs. 
    open var hashValue: Int { 
    return hash 
    } 
} 

public func == (lhs: NSObject, rhs: NSObject) -> Bool { 
    return lhs.isEqual(rhs) 
} 

(Zur Bedeutung von open var finden What is the 'open' keyword in Swift?.)

So NSObject (und alle Unterklassen:

Beide sind über eine NSObject Erweiterung in der Swift Standardbibliothek in ObjectiveC.swift definiert verbunden) entsprechen dem Hashable Protokoll, und die Standard hashValue Implementierung geben Sie die hash zurück Eigenschaft des Objekts.

Eine ähnliche Beziehung besteht zwischen dem isEqual Verfahren des NSObject Protokolls und dem == Operator aus den Equatable Protokoll: NSObject (und alle Subklassen) entspricht das Equatable Protokoll, und die Standard == Umsetzung die isEqual: ruft Methode für die Operanden.

Verwandte Themen