Xcode/Swift - PlayGround

PlayGround) Hashable에 대해서 알아보자

후르륵짭짭 2020. 8. 17. 18:52
728x90
반응형

안녕하세요 후르륵짭짭입니다.

방금 전에 Equtable에 대해서 정리 했는데, 오늘은 Hashable 까지 정리 할려고 합니다.

Hashable은 Dictionary에서 클래스나 구조체를 Key 로 사용할 때, 사용하는 겁니다!

이렇게 dictionary의 [Key : Value]에 Key 값을 Student로 한다면 프로토콜 Hashable을 준수하고 있지 않다고 오류가 나옵니다.

그래서 이렇게 Hashable을 상속 받아 주고 두개의 함수를 넣어 줍니다.

struct Grade{
    let total : Double
}

struct Student :  Hashable{
    let name : String
    let ID : Int
    let grade : Grade
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(grade.total)
    }
    
    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.grade.total == rhs.grade.total && lhs.name == lhs.name
    }
    
}

그럼 하나씩 알아보도록 하겠습니다.

    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.grade.total == rhs.grade.total && lhs.name == lhs.name
    }

이것은 Equtable에서도 본 함수 입니다. 즉, 왼쪽과 오른쪽 같의 동일성 여부를 판단해서 동일한 값이라 생각하면 

Dictionary에 추가하지 않게 하는 겁니다. Dictionary는 C++의 map과 같은 것이고 hash를 사용한 저네릭 함수 입니다!

    func hash(into hasher: inout Hasher) {
        hasher.combine(grade.total)
    }

위에 Student 구조체는 stored 프로퍼티로 Grade 구조체를 가지고 있습니다.

그리고 func == 함수에서 grade를 가지고 비교 하고 있습니다.

따라서 위에 함수를 사용해서 grade를 끌어가지고 와야합니다. 

즉, hash 함수는 동일한 구조체 내에 존재하지 않는 인스턴스 값을 가지고 hashable을 하려고 할 때, 값을 가지고 올 때 사용하는 거입니다.

이렇게 동일한 값이 존재한다면 element에 Hururek의 value 값이 나옵니다.

이렇게 존재하지 않다면 else 문을 수행하게 됩니다!

** 전체 코드 ** 

더보기
struct Grade : Hashable{
    let total : Double
}

struct Student :  Hashable{
    let name : String
    let ID : Int
    let grade : Grade
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(grade.total)
    }
    
    static func == (lhs: Student, rhs: Student) -> Bool {
        return lhs.grade.total == rhs.grade.total && lhs.name == lhs.name
    }
    
}

let Hururuek = Student(name: "Hururuek", ID: 2000 , grade: Grade(total: 3.5))
let ChapChap = Student(name: "Hururuek", ID: 1000 , grade: Grade(total: 2.5))


var dictionary : [Student : Int] = [Hururuek : 1 , ChapChap : 2]

let newStudent = Student(name: "New", ID: 3000, grade: Grade(total: 2.8))

if let element = dictionary[newStudent] {
    print(element)
}
else{
    print("존재 하지 않다")
    dictionary[newStudent] = 1
    print(dictionary[newStudent])
}

 

참고 : 

www.youtube.com/watch?v=9GQZ1aharGg

 

zeddios.tistory.com/498

 

Swift ) Hashable

안녕하세요 :) Zedd입니다. Swift 4.1변경사항 글을 쓰다가..Hashable을 제가 잘 안써서.........ㅎ.......제가..Hashable에 대해...아는건...Dictionary Key로 오려면 Hashable이어야 한다는 것 밖에...그래서 뭔..

zeddios.tistory.com

 

 

728x90
반응형