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


Swift KeyValuePairs用法及代碼示例

結構

KeyValuePairs

一個輕量級的鍵值對集合。

聲明

@frozen struct KeyValuePairs<Key, Value>

概述

當您需要鍵值對的有序集合並且不需要 Dictionary 類型提供的快速鍵查找時,請使用 KeyValuePairs 實例。與真正字典中的鍵值對不同,KeyValuePairs 實例的鍵和值都必須符合 Hashable 協議。

您使用 Swift 字典文字初始化 KeyValuePairs 實例。除了保持原始字典文字的順序外,KeyValuePairs 還允許重複鍵。例如:


let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
                                      "Evelyn Ashford": 10.76,
                                      "Evelyn Ashford": 10.79,
                                      "Marlies Gohr": 10.81]
print(recordTimes.first!)
// Prints "(key: "Florence Griffith-Joyner", value: 10.49)"

使用 KeyValuePairs 時,某些對字典有效的操作會變慢。特別是,要找到與鍵匹配的值,您必須搜索集合的每個元素。以下示例中對 firstIndex(where:) 的調用必須遍曆整個集合以找到與謂詞匹配的元素:


let runner = "Marlies Gohr"
if let index = recordTimes.firstIndex(where: { $0.0 == runner }) {
    let time = recordTimes[index].1
    print("\(runner) set a 100m record of \(time) seconds.")
} else {
    print("\(runner) couldn't be found in the records.")
}
// Prints "Marlies Gohr set a 100m record of 10.81 seconds."

鍵值對作為函數參數

當調用帶有 KeyValuePairs 參數的函數時,您可以傳遞 Swift 字典文字而不會創建 Dictionary。當文字中元素的順序很重要時,此函數尤其重要。

例如,您可以創建一個包含 two-integer 元組列表的 IntPairs 結構,並使用接受 KeyValuePairs 實例的初始化程序。


struct IntPairs {
    var elements: [(Int, Int)]


    init(_ elements: KeyValuePairs<Int, Int>) {
        self.elements = Array(elements)
    }
}

當您準備好創建新的 IntPairs 實例時,使用字典文字作為 IntPairs 初始化程序的參數。 KeyValuePairs 實例保留傳遞的元素順序。


let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
print(pairs.elements)
// Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相關用法


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