Swift 4.0 学习,数据类型教程,字典(Dictionary)学习,字典(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)")
    }

更多更详细教程请访问个人站点: 码出一个长城

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Harvey66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值