Swift 4.0 字典(Dictionary)學習

定義字典常量(常量只有讀操作)

let dictionary1 = ["key1": 888, "key2": 999] 
let dictionary2: [String: Int] = ["key1": 888, "key2": 999]

定義字典變量

var dictionary: [String:Int] = [:]
var dictionary1 = ["key1": 55, "key2": 555]
var dictionary2 = Dictionary<String, Int>()

賦值

dictionary = ["key1": 88, "key2":888, "key3": 8888]

取值

let value = dictionary["key1"]           // 取某個值
let values = dictionary.values.sorted()  // 獲取所有value,從小到大排序
let keys = dictionary.keys.sorted()      // 獲取所有key,從小到大排序

修改value/添加元素

dictionary.updateValue(8, forKey: "key4") // 如果key不存在,則添加新元素
dictionary.updateValue(99, forKey: "key1")// 如果key存在,則修改value

刪除元素

dictionary.removeAll()                 // 刪除所有元素
dictionary.removeValue(forKey: "key1") // 通過查找key來刪除元素
    
let index = dictionary.index(dictionary.startIndex, offsetBy: 1)
dictionary.remove(at: index) // 通過下標刪除元素,offsetBy是第幾個元素

字典遍歷

for item in dictionary {
        
    print("\(item.key) --> \(item.value)")
}
    
for (key, value) in dictionary {
        
    print("\(key) --> \(value)")
}
    
 for sequence in dictionary.enumerated() {
        
    print("\(sequence.offset) --> \(sequence.element.key), \(sequence.element.value)")
}
    
for (offset, item) in dictionary.enumerated() {
        
    print("\(offset) --> \(item.key), \(item.value)")
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容