Swift

KeyValuePairs

Phililip 2024. 1. 28.
728x90

안녕하세요.

 

이번엔 Swift의 Collection 중 하나인 KeyValuePairs에 대해 알아보려고 해요.

 


# KeyValuePairs

KeyValuePairs는 순서가 있는 key-value 쌍을 저장하는 collection 입니다.

 

순서가 있기 때문에 Dictionary보다 value를 찾는 속도가 느립니다.

 

또한 순서가 있기 때문에 Dictinary와는 다르게 element가 Hashable 프로토콜을 준수할 필요가 없습니다.

 

그리고 같은 키를 중복해서 저장할 수 있어요.

 

KeyValuePairs는 ExpressibleByDictionaryLiteral 프로토콜을 준수하기 때문에, dictionary literal을 사용해서 KeyValuePairs 인스턴스를 만들 수 있습니다.

 

let recordTimes: KeyValuePairs = [ // dictionary literal으로 KeyValuePairs 인스턴스 생성
"Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79, // 중복 키 저장 가능
"Marlies Gohr": 10.81
]
print(recordTimes.first!)
// Prints "(key: "Florence Griffith-Joyner", value: 10.49)"
view raw main.swift hosted with ❤ by GitHub

 

특정 key에 매칭된 값을 찾으려면 firstIndex(where:) 함수를 사용해서 모든 element를 검사해야 합니다.

 

let runner = "Marlies Gohr"
if let index = recordTimes.firstIndex(where: { $0.0 == runner }) {
let time = recordTimes[index].1
print("\(runner) set a 100m record of \(time) seconds.")
} else {
print("\(runner) couldn't be found in the records.")
}
// Prints "Marlies Gohr set a 100m record of 10.81 seconds."
view raw main.swift hosted with ❤ by GitHub

 

# KeyValuePairs 파라미터

인자로 전달할 때는 dictionary literal을 전달하면 자동으로 KeyValuePairs 인스턴스가 전달됩니다.

 

func foo(_ elements: KeyValuePairs<String, String>) {
print(elements)
}
foo(["key1": "value1", "key2": "value2"]) // ✅ OK!
view raw main.swift hosted with ❤ by GitHub

 

그러나 dictionary literal로 변수를 생성하고 그 변수를 인자로 넘기는 것은 안됩니다.

(변수는 이미 Dictionary 타입이 되었기 때문이에요.)

 

func foo(_ elements: KeyValuePairs<String, String>) {
print(elements)
}
let elements = ["key1": "value1", "key2": "value2"]
foo(elements) // ❎ Error: Cannot convert value of type '[String : String]' to expected argument type 'KeyValuePairs<String, String>'
view raw main.swift hosted with ❤ by GitHub

 

# KeyValuePairs와 Dictionary 차이점

  KeyValuePairs Dictionary
element 순서 있음 없음
key lookup 속도 느림 빠름
Hashable 프로토콜 준수할 필요 없음 준수해야 함
중복 키 가능 불가능

 

# 참고

 

KeyValuePairs | Apple Developer Documentation

A lightweight collection of key-value pairs.

developer.apple.com

 


이번 글은 여기서 마무리.

 

 

 

반응형

'Swift' 카테고리의 다른 글

propertyWrapper로 UserDefaults 관리  (0) 2024.05.11
@discardableResult  (0) 2024.01.28
Memory Safety  (1) 2024.01.25
클래스(class type) 생성자에 대해 알아보자  (0) 2024.01.21
구조체(value type) 생성자에 대해 알아보자  (0) 2024.01.17