[Swift] Dictionary (딕셔너리)

LEEHAKJIN-VV·2022년 5월 3일
0

Study-Swift 5.6

목록 보기
3/22

참고사이트:
Apple Developer

Dictionary

  • Dicitionary는 elements들이 key-value pair로 이루어진 컬렉션이다.
  • has table의 일종으로서 빠른 접근이 가능하다.

🐶 Declartion

  • 선언은 다음과 같다.
@frozen struct Dictionary<Key, Value> where Key : Hashable

🐶 Dictionary 생성

  • Dictionary 생성은 리터럴을 이용한 방법과 빈 딕셔너리를 생성하는 2가지 방법이 있다.
  • Dictionary는 var, let 모두 가능하다.
  • Hashable protocol유형을 따르는 타입만 Dictionary의 Key로 사용할 수 있다.

🐱 리터럴을 이용한 생성

  • 초기값을 가지고 생성할 때 사용한다.
var responseMessages = [200: "OK",
                        403: "Access forbidden",
                        404: "File not found",
                        500: "Internal server error"]

🐱 빈 Dictionary 생성

  • 초기값이 없이 빈 Dictionary를 생성할 때 ([:])을 사용한다.
var emptyDict: [String:String] = [:]

🐶 Getting and Setting Dictionary Values

  • Dictionary의 values에 접근하는 가장 흔한 방법은 key를 subscript로써 사용하는 것이다. 예시는 다음과 같다.
  • 반환값이 Optional 인스턴스임을 확인할 수 있다.
print(responseMessages[200])
// Optional("OK")

Subscript 란 컬렉션, 리스트, 집합 등 특정 member elements에 간단하게 접근하는 문법이다. 추가적인 메소드 없이 특정 값을 할당하거나 가져올 수 있다. 반환 값은 Optinoal 인스턴스이다. subscript에서 사용한 key에 해당하는 값이 Dicionary에 없을 수도 있기 때문이다.
ex) array[index]

  • 다음 예시는 subcripting을 이용하여 dictionary에 존재하는 key와 존재하지 않는 key를 이용한 응답메시지의 반응이다.
let httpResponseCodes = [200, 403, 301]
for code in httpResponseCodes {
    if let message = responseMessages[code] {
        print("Response \(code): \(message)")
    } else {
        print("Unknown response \(code)")
    }
}
// Prints "Response 200: OK"
// Prints "Response 403: Access forbidden"
// Prints "Unknown response 301"

🐱 Dictionary 추가, 삭제, 수정

  • subscripting을 사용하여 key와 value를 추가, 삭제, 수정을 할 수 있다. 새로 추가하는 key-value pair은 dictionary에 존재하지 않는 key-value로 추가해야 한다.
  • key-value pair 삭제는 삭제하고자하는 key에 해당하는 value를 nil로 수정하면 영구적으로 삭제된다.
// add key-value pair
responseMessages[301] = "Moved permaently"
print(responseMessages[301])
// Prints Optional("Moved permaently")

// update key-value pair
responseMessages[301] = "Deleted permanently"
print(responseMessages[301])
// Prints Optional("Deleted permanently")

// remove key-value pair
responseMessages[500] = nil
print(responseMessages)
// Prints [200: "OK", 301: "Deleted permanently", 403: "Access forbidden", 404: "File not found"]

🐶 Dictionary 다양한 사용

🐱 Dictionary Keys, Values 얻기

  • dictionary의 key, value는 "keys" dictionary 인스턴스의 "keys", "values" property를 이용하여 얻을 수 있다.

Declartion

var keys: Dictionary<Key, Value>.Keys { get }

@frozen struct Values

사용법

  • Dictionary는 Arrays와 다르게 저장 순서를 유지하지 않는다. 그러나 storage에 저장된 key-value pair 순서와 keys property를 이용하여 얻은 key 집합의 순서는 동일한 것을 아래 예시에서 확인할 수 있다.
let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
print(countryCodes)
// Prints "["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]"

for k in countryCodes.keys {
    print(k)
}
// Prints "BR"
// Prints "GH"
// Prints "JP"
  • 위와 마찬가지로 "values" property를 이용하고, value 집합의 순서는 dictionary가 내부적으로 저장된 순서와 동일함을 알 수 있다.
for v in countryCodes.values{
    print(v)
}
// Prints "Ghana"
// Prints "Japan"
// Prints "Brazil"

🐱 Subscripting을 이용한 값 수정

  • dictionary의 인스턴스가 mutable 변수라면 key의 subscript를 이용하여 직접 값에 접근하고 이를 수정할 수 있다.
var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17],
                          "triangular": [1, 3, 6, 10, 15, 21, 28],
                          "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
for key in interestingNumbers.keys {
    interestingNumbers[key]?.sort(by: >)
}

if let numbers = interestingNumbers["primes"]{
    print(numbers)
} else{
    print("It's nill")
}
// Prints "[17, 13, 11, 7, 5, 3, 2]"

🐶 Dictionary 반복

  • 모든 dictionary의 Key-value쌍은 정렬되어 있지 않다. dictionary의 내부를 순회하기 위해서, for-in loop를 사용하여 key-value pair을 얻어 순회한다.

🐱 for-in loop 사용

  • 이때 return 되는 key-value pair는 튜플(tuple)형태이다.
let imagePaths = ["star": "/glyphs/star.png",
                  "portrait": "/images/content/portrait.jpg",
                  "spacer": "/images/shared/spacer.gif"]

for (name, path) in imagePaths{
    print("The path to '\(name)' is '\(path)'.")
}
// Prints The path to 'spacer' is '/images/shared/spacer.gif'.
// Prints The path to 'star' is '/glyphs/star.png'.
// Prints The path to 'portrait' is '/images/content/portrait.jpg'.

🐶 Dictionary value 확인

🐱 contains & firstIndex

  • contains 메소드 또는 firstIndex 메소드를 이용하여 특정 value 값을 확인할 수 있습니다.
let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") })
if let index = glyphIndex {
    print("The '\(imagePaths[index].key)' image is a glyph.")
} else {
    print("No glyphs found!")
}
// Prints "The 'star' image is a glyph.")

0개의 댓글