—————1.初始化( key一定要是可以hash的(String, Int, Float, Double, Bool), value没有要求)
vardict = ["name":"lnj","age":30]
print(dict)
vardict1:Dictionary= ["name":"lnj","age":30]
print(dict1)
vardict2:Dictionary = ["name":"lnj","age":30]
print(dict2)
vardict3:[String:AnyObject] = ["name":"lnj","age":30]
print(dict3)
vardict4:[String:AnyObject] =Dictionary(dictionaryLiteral: ("name","lnj"), ("age",30))
print(dict4)
—————2.数组类型
//不可变数组:
vardict5 = [:]
//可变数组:
letdict6 = [:]
—————3.获取
vardict7 = ["name":"lnj","age":30]
print(dict7["name"]!)
————4.修改
vardict8 = ["name":"lnj","age":30]
dict8["name"] ="iverson"
print(dict8["name"]!)
vardict9 = ["name":"lnj","age":30]
dict9.updateValue("iverson", forKey:"name")
print(dict9["name"]!)
—————5.更新
// updateValue返回一个可选类型,如果字典中不存在需要更新的key,那么返回nil,如果存在返回原始值
vardict10 = ["name":"lnj","age":30]
ifletorignal =dict10.updateValue("iverson", forKey:"name")
{
print(dict10["name"]!)
print(orignal)
}
// updateValue返回一个可选类型,如果字典中不存在需要更新的key,那么返回nil并且会将新的键值对添加到字典中
vardict11 = ["name":"lnj","age":30]
ifletorignal =dict11.updateValue("iverson", forKey:"abc")
{
print(dict11["abc"]!)
print(orignal)
}
print(dict11)
----------6.添加
vardict12 = ["name":"lnj","age":30]
dict12["height"] =175;
----------7.删除
vardict13 = ["name":"lnj","age":30]
dict13.removeValueForKey("name")
// removeValueForKey返回一个可选类型,如果字典中不存在需要删除的key,那么返回nil并且不会执行任何操作,如果存在则删除key对应的值,并且返回被删除的值
vardict14 = ["name":"lnj","age":30]
ifletorignal =dict14.removeValueForKey("names")
{
print(dict14)
print(orignal)
}
print(dict14)
vardict15 = ["name":"lnj","age":30]
dict15.removeAll(keepCapacity:true)
---------8.遍历字典
vardict16 = ["name":"lnj","age":30]
for(key , value)indict16
{
print("key =\(key) value =\(value)")
}
vardict17 = ["name":"lnj","age":30]
forkeyindict17.keys
{
print("key =\(key)")
}
vardict18 = ["name":"lnj","age":30]
forvalueindict18.values
{
print("value =\(value)")
}
网友评论