iOS

Hashable에 대하여

GEEEEEEEE 2023. 2. 10. 00:34

정수 Hash 값을 생성하기 위해 Hasher로 Hash될 수 있는 유형

해쉬는 해쉬 테이블을 통해 Key - Value 로 값을 지정한다. 

 

해쉬 테이블은 내부적으로는 배열로 구성되어 있다. 

 

특정 Key - Value를 저장한다고 하면, 해당 Key를 해쉬 함수란 것을 통해 해시를 하고, 

 

결과 값인 해시 주소 값에 해당하는 해쉬 테이블 슬롯에 Value를 저장한다. 

 

 

1. 구조체 

struct Human: Hashable {
    let name: String
    let age: Int
}
 
let myDict: [Human: Int] = [:]

구조체의 경우, 간단하다. 

 

Equatable과 마찬가지로 만약 구조체 내 프로퍼티가 모두 기본 자료형이므로,

 

Hashable을 채택하는 것만으로 추가 구현 없이 사용이 가능하다.

 

 

2. 클래스 

class Human {
    let name = "Sodeul"
    let age = 28
}
 
extension Human: Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
        hasher.combine(age)
    }
}
 
let myDict: [Human: Int] = [:]

클래스는 Hashable이란, 프로토콜을 준수하는 것도 모자라서 직접 hash 함수를 구현해줘야 한다. 

 

 

class Human {
    let name = "Sodeul"
    let age = 28
}
 
extension Human: Hashable {
    static func == (lhs: Human, rhs: Human) -> Bool {
        return lhs.name == rhs.name && lhs.age == rhs.age
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
        hasher.combine(age)
    }
}
 
let myDict: [Human: Int] = [:]

 

3. 열거형 

 

 

(1) 연관값이 없는 경우 

enum Gender {
    case male
}
 
let myDict: [Gender: Int] = [:]

 

(2) 연관값이 있는 경우

enum Gender: Hashable {
    case male(age: Int)
}
 
let myDict: [Gender: Int] = [:]

 

Hashable을 채택한다고 선언해주고,

 

연관값의 타입(Int)이 모두 Hashable을 채택(구현)하고 있어야 함