Swift里的Dictionary

目录

初始化

访问

修改

updateValue 返回旧值

移除

对应值赋值为nil来从字典里移除一个键值对:

遍历

for in

2、enumerate()遍历,返回的是字典的索引及 (key, value)

方法

keys 、values

isEmpty

使用下标语法来在字典中检索特定键对应的值


初始化

let dictionay = Dictionary<String,String>() //[:]
let letDic = ["A":"Frist","B":"Second","C":"Third"];
var mutableDic:[Int:String] = [1:"One",2:"Two",3:"Three"]

访问

let dicValue = letDic["B"] //"Second"
var mutableDicValue = mutableDic[2] //"Two"

修改

updateValue 返回旧值

let oldValue = mutableDic.updateValue("222", forKey: 2)
print("oldValue is \(oldValue)") 
//oldValue is Optional("Two")//oldValue is Optional("Two")

print("New value is \(mutableDic[2])")
//New value is Optional("222")//New value is Optional("222")

mutableDic[2] = "Two" //插入
print(mutableDic)//[2: "Two", 3: "Three", 1: "One"]

移除

let removValue = mutableDic.removeValue(forKey: 2)
print("removValue is \(removValue)") //removValue is Optional("Two")

对应值赋值为nil来从字典里移除一个键值对:

mutableDic[1] = nil
print(mutableDic) //[3: "Three"]

mutableDic[1] = "one" //添加
mutableDic[2] = "Two" //添加
mutableDic[4] = "Four" //添加

遍历

for in

for (key, value) in letDic {
   print("字典 key \(key) -  字典 value \(value)")
}

打印
字典 key C -  字典 value Third
字典 key B -  字典 value Second
字典 key A -  字典 value Frist

2、enumerate()遍历,返回的是字典的索引及 (key, value)

for (index, value) in letDic.enumerated() {
    print("字典 index \(index) -  字典 (key, value) 对 \(value)")
}

打印
字典 index 0 -  字典 (key, value) 对 (key: "C", value: "Third")
字典 index 1 -  字典 (key, value) 对 (key: "B", value: "Second")
字典 index 2 -  字典 (key, value) 对 (key: "A", value: "Frist")

方法

keys 、values

let keysArray = mutableDic.keys
let valueArray = mutableDic.values
print("输出字典的键\(keysArray)") //输出字典的键[4, 3, 2, 1]
print("输出字典的值\(valueArray)")
//输出字典的值["Four", "Three", "Two", "one"]

isEmpty

print("dictionay isEmpty is:\(dictionay.isEmpty)") //true
print("mutableDic isEmpty is:\(mutableDic.isEmpty)")//false

使用下标语法来在字典中检索特定键对应的值

if let emptyValue = mutableDic[4] {
    print("mutableDic has 4 Key ,value :\(emptyValue)")
} else {
    print("That 4 is not in the mutableDic dictionary.")
}

练习代码: 练习代码


版权声明:本文为zjh467545737原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。