Swift: Protocol Hashable

Wooyo·2023년 9월 4일
0
post-thumbnail

참고 블로그 : https://applecider2020.tistory.com/14

Hashable을 알기 위해 해시값이란?

  • 데이터를 간단한 숫자로 변환한 것
  • 원본 데이터 객체를 해시 함수를 사용하여 64bit int값으로 변환한 것
  • 2개의 데이터 비교시 데이터가 값으면 각 데이터 해쉬값도 값다
let hello: String = "hello"
let hi: String = "hello"
let world: String = "world"

print(hello.hashValue == hi.hashValue) // true
print(hello.hashValue == world.hashValue) // false
  • 단 두개의 서로 다른 데이터가 동일한 해시값을 가질 수 있다.(일정 크기의 int 값은 유한하기 때문)

Hashable 하다는 것은?

  • Hashable 한 타입의 데이터는 해시값을 구할 수 있다.
  • Hashable Protocol을 준수한다는 의미.
  • Hashable Protocol의 정의는 다음과 같다.
public protocol Hashable: Equatable {
	var hashValue: Int { get }
    func hash (into hasher: inout: Hasher)
}

Hashable 한 타입 / 해쉬값은 어디에 사용될까?

  • Swift에서 Set 타입값과 Dictionary 타입의 key값은 Hashable 해야한다.
  • 기본타입 (Int, String 등)은 자동으로 Hashable 하다.
profile
Wooyo의 개발 블로그

0개의 댓글