博客> Swift 4.0 字典(Dictionary)学习
Swift 4.0 字典(Dictionary)学习
2018-11-13 08:22 评论:0 阅读:137 yao7778899
Dictionary swift4.0教程

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

 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>()

赋值

 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) --&gt; \(item.value)")
        }

        for (key, value) in dictionary {

            print("\(key) --&gt; \(value)")
        }

        for sequence in dictionary.enumerated() {

            print("\(sequence.offset) --&gt; \(sequence.element.key), \(sequence.element.value)")
        }

        for (offset, item) in dictionary.enumerated() {

            print("\(offset) --&gt; \(item.key), \(item.value)")
        }

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

收藏
0
sina weixin mail 回到顶部