當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift ExpressibleByDictionaryLiteral用法及代碼示例

協議

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+

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 ExpressibleByDictionaryLiteral。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。