当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。