Notice
Recent Posts
Recent Comments
Link
관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift] Hashable, 해시 (struct 형 해시, class 형 해시) 본문

iOS 기본 (swift)

[iOS - swift] Hashable, 해시 (struct 형 해시, class 형 해시)

jake-kim 2021. 8. 25. 00:08

Hash란?

  • hashing: 임의의 길이를 갖는 데이터(key)를 고정된 길이의 데이터(value)로 매핑하는 의미
  • hash function: key > value 매핑하는 함수
  • hash code: index값
  • hash value: hash code에 해당되는 value 값
  • collision(충돌)
    • chaining으로 해결: hash function을 통해 얻은 hash code값에 이미 데이터가 존재하는 경우 > linked list를 통해 저장
    • LInear Probing으로 해결: hash code += 1 이동
    • Rehashing: Hash Table

Hashable

  • Hashing 기능 프로토콜 - 임의의 길이를 갖는 데이터(key)를 고정된 길이의 데이터(value)로 매핑

  • 사용
    • Dictionary<KeyType, ValueType>, Set<KeyType>: KeyType에 들어가는 자료형들은 모두 Hashable 프로토콜을 준수하고 있는 형태
    • 기본 자료형인 String, Int, Double, enum은 모두 Hashable을 준수하여 key 값으로 사용 가능

ex) enum타입도 KeyType이므로 Set에 바로 사용 가능

enum MyType {
    case a
    case b
    case c
}

var a: Set<MyType> = []
a.insert(.c)
a.insert(.b)
a.remove(.c)

print(a.contains(.c)) // false
print(a.contains(.b)) // true
  • struct는 Hashable 준수해야 사용 가능

struct

Hashable을 준수

  • struct안에 모두 hashable을 준수하는 프로퍼티만 있는 경우, Hashable을 써주기만 하면 완료
struct Person: Hashable {
    var name: String
    var age: Int
}

var s: Set<Person> = []

* 참고

- https://namu.wiki/w/%ED%95%B4%EC%8B%9C

- https://developer.apple.com/documentation/swift/hashable

Comments