協議
Expressible
ExpressibleByDictionaryLiteral
可以使用字典文字初始化的類型。
聲明
protocol ExpressibleByDictionaryLiteral
概述
字典文字是一種編寫鍵值對列表的簡單方法。您使用冒號 (:
) 編寫每個鍵值對,將鍵和值分開。字典文字由一個或多個鍵值對組成,用逗號分隔並用方括號括起來。
要聲明字典,請將字典文字分配給變量或常量:
let countryCodes = ["BR": "Brazil", "GH": "Ghana",
"JP": "Japan", "US": "United States"]
// 'countryCodes' has type [String: String]
print(countryCodes["BR"]!)
// Prints "Brazil"
當上下文提供足夠的類型信息時,您可以使用特殊形式的字典文字,方括號圍繞單個冒號,來初始化一個空字典。
var frequencies: [String: Int] = [:]
print(frequencies.count)
// Prints "0"
符合ExpressibleByDictionaryLiteral 協議
要將使用字典文字初始化的函數添加到您自己的自定義類型,請聲明 init(dictionaryLiteral:)
初始化程序。以下示例顯示了假設的 CountedSet
類型的字典文字初始化程序,它使用 setlike 語義同時跟蹤重複元素的計數:
struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
// implementation details
/// Updates the count stored in the set for the given element,
/// adding the element if necessary.
///
/// - Parameter n: The new count for `element`. `n` must be greater
/// than or equal to zero.
/// - Parameter element: The element to set the new count on.
mutating func updateCount(_ n: Int, for element: Element)
}
extension CountedSet: ExpressibleByDictionaryLiteral {
init(dictionaryLiteral elements: (Element, Int)...) {
self.init()
for (element, count) in elements {
self.updateCount(count, for: element)
}
}
}
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift ExpressibleByIntegerLiteral用法及代碼示例
- Swift ExpressibleByStringInterpolation init(stringInterpolation:)用法及代碼示例
- Swift ExpressibleByUnicodeScalarLiteral用法及代碼示例
- Swift ExpressibleByFloatLiteral init(floatLiteral:)用法及代碼示例
- Swift ExpressibleByIntegerLiteral init(integerLiteral:)用法及代碼示例
- Swift ExpressibleByExtendedGraphemeClusterLiteral用法及代碼示例
- Swift ExpressibleByStringLiteral用法及代碼示例
- Swift ExpressibleByFloatLiteral用法及代碼示例
- Swift ExpressibleByStringInterpolation用法及代碼示例
- Swift ExpressibleByBooleanLiteral init(booleanLiteral:)用法及代碼示例
- Swift ExpressibleByArrayLiteral用法及代碼示例
- Swift ExpressibleByArrayLiteral init(arrayLiteral:)用法及代碼示例
- Swift EnumeratedSequence forEach(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator map(_:)用法及代碼示例
- Swift EnumeratedSequence.Iterator flatMap(_:)用法及代碼示例
- Swift EmptyCollection first(where:)用法及代碼示例
- Swift EmptyCollection index(_:offsetBy:limitedBy:)用法及代碼示例
- Swift EnumeratedSequence drop(while:)用法及代碼示例
- Swift EmptyCollection partition(by:)用法及代碼示例
- Swift EnumeratedSequence.Iterator allSatisfy(_:)用法及代碼示例
- Swift EmptyCollection prefix(upTo:)用法及代碼示例
- Swift EmptyCollection starts(with:)用法及代碼示例
- Swift EnumeratedSequence用法及代碼示例
- Swift EmptyCollection.Iterator split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift EmptyCollection.Iterator starts(with:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ExpressibleByDictionaryLiteral。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。