Hashable 4.1 버전 전 과 후
저는 Swift 4.1버전이하에서 hashValue() 에서 XOR 연산으로 숫자(ex) 16777619), 해쉬값 합치던것을 Swift 4.1이후에는 combine(난수에다가 해쉬값 합치기) 으로 바꾼 것이라고 생각합니다.
너무 당연한가요..?
일단 제가 그렇게 생각한 이유는 옛날코드와 바뀐코드에서의 차이점이 그것뿐 이어서 그렇습니다.
// Swift 4.1 ver 이하 Hashable 작업
struct GridPoint {
var x: Int
var y: Int
}
extension GridPoint: Hashable {
var hashValue: Int {
return x.hashValue ^ y.hashValue &\* 16777619
}
static func == (lhs: GridPoint, rhs: GridPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
// Swift 4.1 ver 이후 Hashable 작업
extension Student : Hashable{
static func == (lhs: Student, rhs: Student) -> Bool {
return lhs.admissionYear == rhs.admissionYear
}
//\* 여기
func hash(into hasher: inout Hasher) {
hasher.combine(admissionYear)
}
}
근데 그렇다고 그냥 넘어가기엔 찝찝해서 내부도 까봤습니다.
-Hasher의 combine 내부-
참고 : https://github.com/apple/swift/blob/main/stdlib/public/core/Hasher.swift
public mutating func combine<H: Hashable>(\_ value: H) {
value.hash(into: &self)
}
Hasher.comebine 코드를 까봤는데 이렇게 되있었습니다. value가 String이라고 예를 들어보겠습니다.
-String의 hash-
참고 : https://github.com/apple/swift/blob/main/stdlib/public/core/StringHashable.swift
public func hash(into hasher: inout Hasher) {
if \_fastPath(self.\_guts.isNFCFastUTF8) {
self.\_guts.withFastUTF8 {
hasher.combine(bytes: UnsafeRawBufferPointer($0))
}
hasher.combine(0xFF as UInt8) // terminator
} else {
\_gutsSlice.\_normalizedHash(into: &hasher)
}
}
String의 hash함수 입니다.
다시 hasher.combine(bytes: UnsafeRawBufferPointer($0))를 사용하니
hasher로 다시 돌아가봤습니다.
-hasher의 combine-
참고 : https://github.com/apple/swift/blob/main/stdlib/public/core/Hasher.swift
public mutating func combine(bytes: UnsafeRawBufferPointer) {
_core.combine(bytes: bytes)
}
_core의 combine을 사용하네요.. _core 가 뭔지 들어가봤습니다.
internal struct _Core {
@inline(__always)
internal init(seed: Int) {
self.init(state: _State(seed: seed))
}
}
뭔진 모르겠지만 seed가 있는 걸로보아 4.1 버전 이하에서 쓰이던 16777619 숫자같은 난수로 만든 무언가
에다가 combine(XOR같은 연산)을 해준것이 아닐까요. combine 내부보니 XOR처럼 단순하진 않고 뭐 복잡하게 되어있었습니다만..
이것도 제 추측이어서 틀릴 수 있습니다.
다른 의견 있으시면 댓글로 코멘트 남겨주시면 감사하겠습니다!
'IOS Swift' 카테고리의 다른 글
MVC와 MVVM의 차이점 및 장단점 (0) | 2021.09.09 |
---|---|
Optional 이란? (2) | 2021.09.02 |
[자료구조] HashTable 이란? (0) | 2021.08.29 |
Hashable 이란? - Swift (2) | 2021.08.24 |
Tuple이란? - Swift (0) | 2021.08.17 |