swift基础语法(字典)

字典的 Key类型必须遵循 Hashable协议,就像合集的值类型。

1、定义字典

let dict: [String : Any] = ["name": "zhangmingjun", "age": 20, "height": 1.87]
print(dict)

2、创建空字典

var dictM = [String : Any]()

3、添加元素

dictM["name"] = "zhangmignjun"
dictM["age"] =  20
dictM["height"] = 1.87
dictM["weight"] = 65
print(dictM)

4、判断是否为空

if dictM.isEmpty {
    print("is empty.")
} else {
    print("is not empty.")
}

5、修改元素: 如果字典中已有对应的key,那么直接自改对应key的值;字典中没有对应的key,那么添加对应的key/value

dictM["name"] = "liu"

6、获取某一个元素

print(dictM["age"]!)

7、遍历字典

for key in dictM.keys {
    print(key)
}

for value in dictM.values {
    print(value)
}

for (key, value) in dictM {
     print(key)
     print(value)
}

1、定义字典

let dict: [String : Any] = ["name": "zhangmingjun", "age": 20, "height": 1.87]
print(dict)

8、合并字典

var dict1: [String : Any] = ["name" : "why", "age": 1.88]
let dict2: [String : Any] = ["height" : 1.56, "phone": "123q232"]

for (key,value) in dict2 {
    dict1[key] = value
}
print(dict1)

你可能感兴趣的:(swift基础语法(字典))