참고사이트:
Apple Developer
@frozen struct Dictionary<Key, Value> where Key : Hashable
var responseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
var emptyDict: [String:String] = [:]
print(responseMessages[200])
// Optional("OK")
Subscript 란 컬렉션, 리스트, 집합 등 특정 member elements에 간단하게 접근하는 문법이다. 추가적인 메소드 없이 특정 값을 할당하거나 가져올 수 있다. 반환 값은 Optinoal 인스턴스이다. subscript에서 사용한 key에 해당하는 값이 Dicionary에 없을 수도 있기 때문이다.
ex) array[index]
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"
// 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"]
var keys: Dictionary<Key, Value>.Keys { get }
@frozen struct Values
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"
for v in countryCodes.values{
print(v)
}
// Prints "Ghana"
// Prints "Japan"
// Prints "Brazil"
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]"
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'.
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.")