实例下标
subscript(_:
subscript(_:default:)
使用给定键访问值,如果找不到该键,则回退到给定的默认值。
声明
subscript(
key: Key,
default defaultValue: @autoclosure () -> Value
) -> Value { get set }
当
Key
符合 Hashable
时可用。返回值
字典中与key
相关的值;否则,defaultValue
。
参数
key
在字典中查找的键。
defaultValue
如果字典中不存在
key
,则使用默认值。
概述
如果您想要特定键的值,或者当字典中不存在该键时,请使用此下标。此示例使用带有消息的下标,以防无法识别 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
类型具有值语义时,您可以使用此下标对字典中的值执行就地操作。以下示例在计算字符串中每个字母的出现次数时使用此下标:
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, default: 0] += 1
使用 letter
的值执行时,该值还不是 letterCounts
中的键,从下标返回指定的默认值 ( 0
),递增,然后添加到该下的字典中钥匙。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift Dictionary subscript(_:)用法及代码示例
- Swift Dictionary suffix(from:)用法及代码示例
- Swift Dictionary suffix(_:)用法及代码示例
- Swift Dictionary sorted(by:)用法及代码示例
- Swift Dictionary split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代码示例
- Swift Dictionary shuffled(using:)用法及代码示例
- Swift Dictionary shuffled()用法及代码示例
- Swift Dictionary allSatisfy(_:)用法及代码示例
- Swift Dictionary values用法及代码示例
- Swift Dictionary dropFirst(_:)用法及代码示例
- Swift Dictionary firstIndex(where:)用法及代码示例
- Swift Dictionary first(where:)用法及代码示例
- Swift Dictionary merge(_:uniquingKeysWith:)用法及代码示例
- Swift Dictionary isEmpty用法及代码示例
- Swift Dictionary reduce(_:_:)用法及代码示例
- Swift Dictionary init(uniqueKeysWithValues:)用法及代码示例
- Swift Dictionary makeIterator()用法及代码示例
- Swift Dictionary randomElement()用法及代码示例
- Swift Dictionary init(grouping:by:)用法及代码示例
- Swift Dictionary dropLast(_:)用法及代码示例
- Swift Dictionary min(by:)用法及代码示例
- Swift Dictionary max(by:)用法及代码示例
- Swift Dictionary updateValue(_:forKey:)用法及代码示例
- Swift Dictionary removeValue(forKey:)用法及代码示例
- Swift Dictionary map(_:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 Dictionary subscript(_:default:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。