[Swift] Collection Type - Dictionary

Minjeong Park·2021년 10월 16일
0

Swift 문법

목록 보기
7/9

📕 Dictionary


공식 도큐먼트

Dictionary는 Key와 Value 형태로 데이터를 저장하는 컨테이너다.
Array와 가장 큰 차이점은 순서가 보장되지 않는다는 것이다.

각각의 Value는 유일한 키 값에 연결되어 있어서,
Key값은 Dictionary안에서 value를 찾기 위하 식별자 역할을 한다.
(회원정보에서 주민등록번호가 Key, 이름이나 기타 정보가 Value가 될 수 있다.)

Key값은 Hashable 해야 한다. 즉, 그 자체로 유일하게 표현 가능 해야 한다.
Swift의 기본 자료형(Int, String, Float...)은 기본적으로 Hashable하기 때문에 Dictionary의 Key로 사용 가능하다.

생성

var dic1 : [Int : String] = [:]
var dic2 = [Int : String]()
var dic3 : Dictionary = [Int:String]()
var dic4 : Dictionary<Int, String> = Dictionary<Int, String>() // 👍
var myMenu : Dictionary<String, Int> = ["Americano":3200, "Latte":3700]

이 중 하나만 알아도 사용하는데 문제는 없다!

생성 && 초기화

var myMenu1 : Dictionary<String, Int> = ["Americano":3200, "Latte":3700]
var myMenu2 : Dictionary = ["Americano":3200, "Latte":3700]
var myMenu3 : [String : Int] = ["Americano":3200, "Latte":3700]
var myMenu4 = ["Americano":3200, "Latte":3700] // 타입 추론


myMenu4타입 추론을 통해 [String:Int]인 Dictionary라는 것을 알 수 있다.
또, Dictionary는 순서가 없기 때문에 순서가 보장이 안되는 것을 확인할 수 있다.

데이터 수정

Key값을 알고 있다면 Value를 수정할 수 있다.

  • dictionaryName[Key] = NewValue : 해당 Key의 Value를 NewValue로 바꾼다.
  • func updateValue(Value, forKey: Key) -> Value?
    • 이때 Key는 존재하는 Key여야 한다.
var lectures : Dictionary<String, String> = ["CSE1294":"Python", "CSE3928":"Computer Architecture"]
print(lectures) 
//["CSE3928": "Computer Architecture", "CSE1294": "Python"]

lectures["CSE3928"] = "Operating System"
print(lectures)
//["CSE3928": "Operating System", "CSE1294": "Python"]

lectures.updateValue("Machine Learning", forKey: "CSE3928")
print(lectures)
//["CSE3928": "Machine Learning", "CSE1294": "Python"]

데이터 추가

  • func updateValue(Value, forKey: Key) -> Value?
    • 이때 Key는 기존에 존재하지 않는 Key여야 한다.
lectures.updateValue("Computer Vision", forKey: "CSE3201")
// Print ["CSE3928": "Machine Learning", "CSE1294": "Python", "CSE3201": "Computer Vision"]

⚠️ 값에 접근하기

Value에 접근하는 것은 앞서 데이터 수정에서 보았던 것처럼 DictionaryName[Key]로 할 수 있다.
특이한 점은 Swift 입장에서 이 Key에 대한 Value가 있는지 없는지 모르기 때문에 Value를 Optional형태로 반환한다.
따라서 값을 사용할 때는 !(Unwrapping, 언래핑)을 사용해 값을 꺼내온다.

print(lectures["CSE3928"])
    //Print Optional("Machine Learning")
print(lectures["CSE3928"]!) // 언래핑
    // Print Machine Learning

값 삭제하기

  • removeValue(forKey:)
  • removeAll(_:)
lectures.removeValue(forKey: "CSE3928")
lectures.removeAll()
profile
아자아잣

0개의 댓글