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


Swift Dictionary init(uniqueKeysWithValues:)用法及代碼示例

初始化器

init(uniqueKeysWithValues:)

從給定序列中的鍵值對創建一個新字典。

聲明

init<S>(uniqueKeysWithValues keysAndValues: S) where S : Sequence, S.Element == (Key, Value)

返回值

使用 keysAndValues 的元素初始化的新字典。

參數

keysAndValues

用於新字典的鍵值對序列。 keysAndValues 中的每個鍵都必須是唯一的。

詳述

當您有一係列具有唯一鍵的鍵值元組時,您可以使用此初始化程序來創建字典。將具有重複鍵的序列傳遞給此初始化程序會導致運行時錯誤。如果您的序列可能有重複的鍵,請改用 Dictionary(_:uniquingKeysWith:) 初始化程序。

以下示例使用字符串數組作為鍵和可數範圍內的整數作為值創建一個新字典:


let digitWords = ["one", "two", "three", "four", "five"]
let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5))
print(wordToValue["three"]!)
// Prints "3"
print(wordToValue)
// Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]"

可用版本

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

相關用法


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