Dictionary
1. Tạo Dictionary
Phần tiêu đề “1. Tạo Dictionary”// Dictionary literalvar scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
// Empty dictionaryvar emptyDict: [String: Int] = [:]var anotherDict = [String: String]()
// Type inferencevar ages = ["Alice": 25, "Bob": 30] // [String: Int]2. Truy cập values
Phần tiêu đề “2. Truy cập values”let scores = ["Alice": 95, "Bob": 87]
// Subscript - trả về Optionallet aliceScore = scores["Alice"] // Optional(95)
if let score = scores["Alice"] { print("Alice: \(score)")}
// Default valuelet bobScore = scores["Bob"] ?? 03. Thêm/Sửa
Phần tiêu đề “3. Thêm/Sửa”var scores = ["Alice": 95]
// Thêm mớiscores["Bob"] = 87
// Sửascores["Alice"] = 98
// updateValue - trả về old valueif let oldScore = scores.updateValue(90, forKey: "Alice") { print("Old score: \(oldScore)")}4. Xóa
Phần tiêu đề “4. Xóa”var scores = ["Alice": 95, "Bob": 87]
// Gán nilscores["Alice"] = nil
// removeValueif let removed = scores.removeValue(forKey: "Bob") { print("Removed: \(removed)")}
// Xóa tất cảscores.removeAll()5. Duyệt Dictionary
Phần tiêu đề “5. Duyệt Dictionary”let scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
// Keys và valuesfor (name, score) in scores { print("\(name): \(score)")}
// Chỉ keysfor name in scores.keys { print(name)}
// Chỉ valuesfor score in scores.values { print(score)}6. Dictionary methods
Phần tiêu đề “6. Dictionary methods”let scores = ["Alice": 95, "Bob": 87]
print(scores.count) // 2print(scores.isEmpty) // falseprint(scores.keys) // ["Alice", "Bob"]print(scores.values) // [95, 87]
// Convert keys/values to Arraylet names = Array(scores.keys)let scoresList = Array(scores.values)📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”[Key: Value]- Dictionary typedict["key"]- Trả về Optionaldict["key"] = value- Thêm/sửadict["key"] = nil- Xóakeys,values- Lấy keys/values- Duyệt với
for (key, value) in dict