定义字典常量(常量只有读操作)

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)")
}

本文由 Harvey 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论