Swift 字典
封面图
•
2025-10-18
•
Swift
2
0
0
0
在 **Swift** 中,**字典(Dictionary)** 是一种用于存储键值对(key-value pairs)的数据结构。每个键(key)都必须是唯一的,并且可以用来查找对应的值(value)。 --- ## 📌 Swift 字典的基本语法 ### 1. 声明一个空字典 ```swift var myDictionary = [String: Int]() ``` 或者使用类型推断: ```swift var myDictionary: [String: Int] = [:] ``` ### 2. 初始化一个带有值的字典 ```swift var person = ["name": "Alice", "age": 30] ``` ### 3. 使用字面量初始化(更清晰) ```swift var scores = ["Alice": 90, "Bob": 85, "Charlie": 95] ``` --- ## 🔍 字典操作 ### 1. 访问值 ```swift print(scores["Alice"]) // 输出: Optional(90) ``` 如果想直接获取值(不带 `Optional`),可以用 `if let` 或 `guard let`: ```swift if let aliceScore = scores["Alice"] { print("Alice's score: $aliceScore)") } ``` ### 2. 添加或更新键值对 ```swift scores["David"] = 88 // 添加 scores["Alice"] = 95 // 更新 ``` ### 3. 删除键值对 ```swift scores.remove(forKey: "Bob") ``` 或者直接赋值为 `nil`: ```swift scores["Charlie"] = nil ``` ### 4. 遍历字典 ```swift for (name, score) in scores { print("$name: $score)") } ``` 也可以只遍历键或值: ```swift for name in scores.keys { print(name) } for score in scores.values { print(score) } ``` --- ## 🧠 注意事项 - **键必须是可哈希的(Hashable)**:例如 `String`, `Int`, `Double`, `Date` 等。 - **值可以是任意类型**,包括自定义类型(只要它们遵循 `Hashable` 协议)。 - **字典是无序的**:不能保证键值对的顺序。 --- ## ✅ 示例代码 ```swift var books: [String: String] = [ "1984": "George Orwell", "Moby Dick": "Herman Melville", "The Great Gatsby": "F. Scott Fitzgerald" ] // 添加 books["Pride and Prejudice"] = "Jane Austen" // 更新 books["1984"] = "George Orwell (Revised)" // 删除 books.remove(forKey: "Moby Dick") // 遍历 for (title, author) in books { print("$title by $author") } ``` --- 如果你有特定的使用场景或问题(比如如何处理嵌套字典、转换字典等),欢迎继续提问!
上一篇:
Swift 数组
下一篇:
Swift 函数
标题录入,一次不能超过6条
返回顶部
留言
留言
评论