Bibi's DevLog πŸ€“πŸŽ

Dictionary - subscript(_: default:) λ³Έλ¬Έ

πŸ“±πŸŽ iOS/🍏 Apple Developer Documentation

Dictionary - subscript(_: default:)

λΉ„λΉ„ bibi 2022. 8. 25. 23:59

subscript(_: default:) (Dictionary)

https://developer.apple.com/documentation/swift/dictionary/subscript(_:default:)

  • λ”•μ…”λ„ˆλ¦¬μ—μ„œ 주어진 킀에 ν•΄λ‹Ήν•˜λŠ” 값을 λ¦¬ν„΄ν•˜κ³ , λ§Œμ•½ ν•΄λ‹Ήν•˜λŠ” ν‚€κ°€ μ—†μœΌλ©΄ default둜 μ§€μ •λœ 값을 λ°˜ν™˜ν•œλ‹€.
  • key : λ”•μ…”λ„ˆλ¦¬μ—μ„œ 찾을 ν‚€
    • keyκ°€ Hashable 을 μ€€μˆ˜ν•΄μ•Ό μ‚¬μš© κ°€λŠ₯함
  • 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).