Bibi's DevLog ๐ค๐
Dictionary - subscript(_: default:) ๋ณธ๋ฌธ
๐ฑ๐ iOS/๐ Apple Developer Documentation
Dictionary - subscript(_: default:)
๋น๋น bibi 2022. 8. 25. 23:59subscript(_: default:)
(Dictionary)
https://developer.apple.com/documentation/swift/dictionary/subscript(_:default:)
- ๋์
๋๋ฆฌ์์ ์ฃผ์ด์ง ํค์ ํด๋นํ๋ ๊ฐ์ ๋ฆฌํดํ๊ณ , ๋ง์ฝ ํด๋นํ๋ ํค๊ฐ ์์ผ๋ฉด
default
๋ก ์ง์ ๋ ๊ฐ์ ๋ฐํํ๋ค. - key : ๋์
๋๋ฆฌ์์ ์ฐพ์ ํค
- key๊ฐ
Hashable
์ ์ค์ํด์ผ ์ฌ์ฉ ๊ฐ๋ฅํจ
- key๊ฐ
- defaultValue : ๋์ ๋๋ฆฌ์ ํด๋น ํค๊ฐ ์กด์ฌํ์ง ์์ ๋ ์ฌ์ฉํ ๊ธฐ๋ณธ๊ฐ
- ๋์
๋๋ฆฌ์ ํน์ ํค๊ฐ ์กด์ฌํ ๋๋ ๊ทธ ๊ฐ์ ๋ฆฌํดํ๊ณ , ์กด์ฌํ์ง ์์ ๋๋ default value๋ฅผ ๋ฆฌํดํ๋ ์๋ธ์คํฌ๋ฆฝํธ.
- ์๋ ์์๋ HTTP ์๋ต ์ฝ๋๊ฐ ์ธ์๋์ง ์๋ ๊ฒฝ์ฐ ์ฌ์ฉํ ๋ฉ์์ง๋ก ์๋ธ์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํ๋ค:
var responseMessages = [200: "OK",
403: "Access forbidden",
404: "File not found",
500: "Internal server error"]
let httpResponseCodes = [200, 403, 301]
for code in httpResponseCodes {
let message = responseMessages[code, default: "Unknown response"]
print("Response \(code): \(message)")
}
// Prints "Response 200: OK"
// Prints "Response 403: Access forbidden"
// Prints "Response 301: Unknown response"
- ๋์ ๋๋ฆฌ์ value ํ์ ์ด value semantics์ ๊ฐ์ง ๋, ์ด ์๋ธ์คํฌ๋ฆฝํธ๋ฅผ ์ฌ์ฉํด ๋์ ๋๋ฆฌ ๋ด์์ ๊ฐ์ ๋ํด ์ ์๋ฆฌ(in-place) ์ฐ์ฐ์ ํ ์ ์๋ค.
let message = "Hello, Elle!"
var letterCounts: [Character: Int] = [:]
for letter in message {
letterCounts[letter, default: 0] += 1
}
// letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...]
- letterCounts์ ํค๊ฐ ์กด์ฌํ์ง ์๋ ์ํ์์ letter์ ๊ฐ์ ๋ํด
letterCounts[letter, default: 0] += 1
์ฐ์ฐ์ด ์คํ๋ ๋, - ์ง์ ๋์ด ์๋ defalut value์ธ 0์ด ์๋ธ์คํฌ๋ฆฝํธ๋ก๋ถํฐ ๋ฐํ๋๊ณ , 1์ด ์ฆ๊ฐ๋ ๋ค, ๊ทธ ํค์ ๋ํ ๊ฐ์ผ๋ก ๋์ ๋๋ฆฌ์ ์ถ๊ฐ๋๋ค.
๋ ธํธ
๋์ ๋๋ฆฌ์ value ํ์ ์ด ํด๋์ค์ผ ๋๋ ์ด ์๋ธ์คํฌ๋ฆฝํธ๋ก ๋์ ๋๋ฆฌ ๊ฐ์ ์์ ํ๊ธฐ ์ํด ์ฌ์ฉํ์ง ๋ง์ญ์์ค. ๊ทธ๋ฌํ ๊ฒฝ์ฐ์๋, ํด๋น ์ฐ์ฐ ์ดํ์ default value์ key๊ฐ ๋์ ๋๋ฆฌ๋ก ๋ค์ ์จ์ง์ง ์์ต๋๋ค(not written back).
'๐ฑ๐ iOS > ๐ Apple Developer Documentation' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๐ / UIKit] UINavigationController (1) | 2022.09.23 |
---|---|
About the App Launch Sequence ์ฑ ์คํ ์ํ์ค์ ๋ํ์ฌ (0) | 2022.08.27 |
[Swift] .zip(_:_:) : ๋ ์ํ์ค ํฉ์น๊ธฐ (0) | 2022.06.21 |
[Foundation] UserDefaults (1) | 2022.06.17 |
UINavigationBar์ ์์ ๋ฃ๊ธฐ (Customizing the appearance of UINavigationBar) (0) | 2022.05.25 |