Dictionary trong Swift
1. Tạo Dictionary
// Dictionary literal
var scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
// Empty dictionary
var emptyDict: [String: Int] = [:]
var anotherDict = [String: String]()
// Type inference
var ages = ["Alice": 25, "Bob": 30] // [String: Int]2. Truy cập values
let scores = ["Alice": 95, "Bob": 87]
// Subscript - trả về Optional
let aliceScore = scores["Alice"] // Optional(95)
if let score = scores["Alice"] {
print("Alice: \(score)")
}
// Default value
let bobScore = scores["Bob"] ?? 03. Thêm/Sửa
var scores = ["Alice": 95]
// Thêm mới
scores["Bob"] = 87
// Sửa
scores["Alice"] = 98
// updateValue - trả về old value
if let oldScore = scores.updateValue(90, forKey: "Alice") {
print("Old score: \(oldScore)")
}4. Xóa
var scores = ["Alice": 95, "Bob": 87]
// Gán nil
scores["Alice"] = nil
// removeValue
if let removed = scores.removeValue(forKey: "Bob") {
print("Removed: \(removed)")
}
// Xóa tất cả
scores.removeAll()5. Duyệt Dictionary
let scores = ["Alice": 95, "Bob": 87, "Charlie": 92]
// Keys và values
for (name, score) in scores {
print("\(name): \(score)")
}
// Chỉ keys
for name in scores.keys {
print(name)
}
// Chỉ values
for score in scores.values {
print(score)
}6. Dictionary methods
let scores = ["Alice": 95, "Bob": 87]
print(scores.count) // 2
print(scores.isEmpty) // false
print(scores.keys) // ["Alice", "Bob"]
print(scores.values) // [95, 87]
// Convert keys/values to Array
let names = Array(scores.keys)
let scoresList = Array(scores.values)📝 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
Last updated on
Swift