본문 바로가기
카테고리 없음

Swift - Dictionary

by chozjjae 2022. 5. 23.

Dictionary란 ?

데이터를 키(key) - 값(value) 쌍의 형태로 저장하고 관리하는 컬렉션을 의미한다.

 

특징 

  • Generic 구조체로 이루어져있다.
  • 배열과 비슷한 목적의 작업을 하지만 순서가 없다.
  • Dictionary에 저장된 각 항목은 값을 참조하고 접근하는데 사용되는 유일한 키와 연결되어 있다.
  • Dictionary의 키는 해시 가능한 타입이어야 한다.
  • Swift의 기본 타입(자료형 : String, Int, Double, Bool 등)은 해쉬가능 하므로 Dictionary의 key로 사용할 수 있다.
  • Optional, Array, Set도 키로 가능하다.

*key 만 Hashable protocol을 만족하면 된다.

where절, where문은 부가적인 조건을 추가하거나 타입에 대한 제약을 추가할 때 사용한다.

 

Dictionary 사용예제

//Dictionary 만드는 과정

//빈 Dictionary
var x = [Int:String]() 
var y : Dictionary<String,String> = [:]

//값이 들어가는 Dictionary
var a : [Int:String] = [1:"일", 2:"이",3: "삼"]
var b : Dictionary<Int, String> = [1:"하나", 2: "둘", 3:"셋"]
var c = [1:"원", 2:"투", 3:"쓰리"]

var b1 : [String:Double] = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
var b2 : Dictionary<String,Double> = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
var b3 = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]

let c1 : Dictionary<String, String> = ["빨강":"red", "초록":"green", "파랑":"blue"]
let c2 : [String:String] =  ["빨강":"red", "초록":"green", "파랑":"blue"]
let c3 = ["빨강":"red", "초록":"green", "파랑":"blue"]

Dictionary의 타입, 자료형 알아보기

//Dictionary 만드는 과정
var x = [Int:String]() //빈 Dictionary
var y : Dictionary<String,String> = [:]

//값이 들어가는 Dictionary
var a : [Int:String] = [1:"일", 2:"이",3: "삼"]

var b : Dictionary<String,Double> = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]

let c = ["빨강":"red", "초록":"green", "파랑":"blue"]

print(type(of:a)) //Dictionary<Int, String>
print(type(of:b)) //Dictionary<String, Double>
print(type(of:c)) //Dictionary<String, String>

Dictionary key를 이용한 항목 접근

  • Dictionary의 key로 value를 접근하면 옵셔널 형으로 나온다.
var number : [Int:String] = [1 : "일", 2 : "이", 3: "삼"]
print(number)//[1: "일", 2: "이", 3: "삼"]
print(number.count) //3
print(number[1],number[2],number[3])
//Optional("일") Optional("이") Optional("삼")
print(number[1]!, number[2]!, number[3]!)
//일, 이, 삼
print(number[0]) //nil

옵셔널 바인딩 또는 강제 언래핑을 통하여 언래핑 된 value값을 얻을 수 있다.
var number : [Int:String] = [1 : "일", 2 : "이", 3: "삼"]
number[0] = "영"
number[4] = "사"
print(number)
//[0: "영", 2: "이", 1: "일", 4: "사", 3: "삼"]

print(number[0]!,number[3]!)// 영, 삼
//강제 언래핑
if let num = number[1]{
    print(num) //일
} //옵셔널 바인딩

Dictionary key를 이용한 항목 변경, 값 변경

var number : [Int:String] = [1 : "일", 2 : "이", 3: "삼"]
number[0] = "영"
number[4] = "사"
print(number)
//[0: "영", 2: "이", 1: "일", 4: "사", 3: "삼"]

number.updateValue("둘", forKey:2)
print(number)
//[4: "사", 0: "영", 2: "둘", 3: "삼", 1: "일"]

Dictionary key를 이용한 항목 삭제, 주소를 이용한 값 삭제

var number : [Int:String] = [1 : "일", 2 : "이", 3: "삼"]
number[0] = "영"
number[4] = "사"
print(number)
//[0: "영", 2: "이", 1: "일", 4: "사", 3: "삼"]

number[2] = nil
print(number)
//[1: "일", 3: "삼", 0: "영", 4: "사"]
number.removeValue(forKey:1)
print(number)
//[3: "삼", 0: "영", 4: "사"]

var w : [String:Double] = ["김보통":60.5,"이갈비":42.7,"엄청군":123.4]
print(w)//["이갈비": 42.7, "엄청군": 123.4, "김보통": 60.5]
print(w.count) //3
print(w["김보통"]) //Optional(60.5)
print(w["김보통"]!) //60.5
print(w["홍길동"]) //nil 출력

w["홍길동"] = 80.0 //값 변경
w["김보통"] = 70.0 //값 변경
w.updateValue(90.0,forKey:"이갈비") //값 변경
print(w) //["이갈비": 90.0, "김보통": 70.0, "홍길동": 80.0, "엄청군": 123.4]
w.removeValue(forKey:"엄청군") //값 삭제
print(w) //["이갈비": 90.0, "김보통": 70.0, "홍길동": 80.0]
w["이갈비"] = nil
print(w) //["김보통": 70.0, "홍길동": 80.0]

for ~ in으로 Dictionary 항목 접근하기

let colors = ["빨강":"red","초록":"green","파랑":"blue"]
print(colors)
//["파랑": "blue", "빨강": "red", "초록": "green"]
for color in colors{
    print(color)
}
//(key: "파랑", value: "blue")
//(key: "빨강", value: "red")
//(key: "초록", value: "green")

for (cKor,cEng) in colors { //Tuple
print(cKor,cEng)
}
//파랑 blue
//빨강 red
//초록 green

Dictionary 정렬

let colors = ["빨강":"red","초록":"green","파랑":"blue"]
print(colors)
//["파랑": "blue", "빨강": "red", "초록": "green"]
var order = colors.keys.sorted() //오름차순으로 정렬
print(order) //["빨강", "초록", "파랑"]
order = colors.keys.sorted(by:>) //내림차순으로 정렬
print(order) //["파랑", "초록", "빨강"]

order = colors.values.sorted()//오름차순으로 값 정렬
print(order)//["blue", "green", "red"]
order = colors.values.sorted(by:>) //내림차순으로 값 정렬
print(order)//["red", "green", "blue"]


var oColor = colors.sorted(by:<) //key로 정렬이 된다.
print(oColor)
//[(key: "빨강", value: "red"), (key: "초록", value: "green"), (key: "파랑", value: "blue")]

Keys나 Values형을 Array형으로 만들기

let colors = ["빨강":"red","초록":"green","파랑":"blue"]
print(colors)
//["파랑": "blue", "빨강": "red", "초록": "green"]

var kColor = colors.keys
print(kColor) //["파랑", "초록", "빨강"]
print(type(of:kColor)) //keys

var kColor1 = [String](colors.keys)
print(kColor1) //["빨강", "초록", "파랑"]
print(type(of:kColor1)) //Array<String>

var eColor = colors.values
print(eColor) //["red", "green", "blue"]
print(type(of:eColor))//values

var eColor1 = [String](colors.values)
print(eColor1) //["green", "red", "blue"]
print(type(of:eColor1)) //Array<String>

항목의 개수 출력(count), 비어 있는지(isEmpty) 알아내기

let colors = ["빨강":"red","초록":"green","파랑":"blue"]
print(colors)
//["파랑": "blue", "빨강": "red", "초록": "green"]

var y : Dictionary<String,String> = [:] //빈 Dictionary

//colors는 빈 Dictionary가 아니기 때문에 else값 출력
if colors.isEmpty{
    print("비어 있습니다")
}
else{
    print(colors.count) //3
}

if y.isEmpty{ //y Dictionary는 비어있기 때문에 if 값 출력
    print("비어 있습니다.") //출력력
}
else{
    print(colors.count)
}

참고자료 

youtube - smile han 자료를 참고하였습니다.