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)")
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容