Tôi muốn xóa cặp khóa-giá trị khỏi từ điển như trong ví dụ nếu có thể.
var dict: Dictionary<String,String> = [:]
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
Tôi muốn xóa cặp khóa-giá trị khỏi từ điển như trong ví dụ nếu có thể.
var dict: Dictionary<String,String> = [:]
var willRemoveKey = "SomeKey"
dict.removePair(willRemoveKey) //that's what I need
Câu trả lời:
Bạn có thể sử dụng cái này:
dict[willRemoveKey] = nil
hoặc cái này:
dict.removeValueForKey(willRemoveKey)
Sự khác biệt duy nhất là giá trị thứ hai sẽ trả về giá trị đã loại bỏ (hoặc nil nếu nó không tồn tại)
dict.removeValue(forKey: willRemoveKey)
nilluôn xóa khóa. Để gán một nilgiá trị true trong từ điển với loại Giá trị tùy chọn, hãy gán .some(nil).
Xóa bằng Kiểm tra điều kiện trong LOOP
var eventDateDict = [String:String]()
//Declarations
var tempDict = eventDateDict
for value in tempDict{
let getDate = value.key
if getDate < Date(){
eventDateDict.removeValue(forKey: value.key)
}
}
dict.removeValue(willRemoveKey)vì có vẻ như .removeValueForKey đã được đổi tên - cảm ơn bạn đã giúp đỡ!