Learning from the Geek Academy: a dictionary in Swift
Tool: Xcode6.4
Directly on the basis of the sample code, more knocks more experience will have a harvest: hundred see not like a knock, a knock will
1 Import Foundation2 3 //Statement of the dictionary4var dic1:dictionary <String,String>5 var scores: [String:int]6 //then create a dictionary7Dic1 = dictionary<string,string>()8Scores = dictionary<string,int> (minimumcapacity:5)9 Tenvar emptydic: [String:double] = [:]//Empty Dictionary One println (emptydic.isempty) A - //Determine whether a dictionary is mutable by constants and variables -var person = [" Age": -, the "name":"Heyang", - "Height":178] -println (person[" Age"]!) -println (person["Weight"])//non-existent key, returned as nil +person["name"] ="Heyang" -println (person["name"]!) + Aperson["Weight"] = - atprintln"The dictionary is unordered: \ (person)")//set value to a nonexistent key, and the dictionary will add key-value to the - - //var height:int = person["height"] will error, because the element of person is nsobject so the above dictionary person is not rigorous -var person_1 = [" Age":" -", - "name":"Heyang", - "Height":"178"] invar height_1:string? = person_1["Height"] - ifHeight_1! =Nil { toprintln (height_1!) + } - //Updatevalue (Value:value, Forkey:key) the ifLet oldname = Person_1.updatevalue (" the", Forkey:"Height"){ *println"The original value is: \ (oldname)") $ }Panax Notoginsengprintln"now the values are:"+person_1["Height"]!) - thePrint"Traversal:") + for(Key,value)inchperson_1{ APrint"\ (key): \ (value)") the } + - println () $ //How to delete a dictionary $Person.removeall (keepcapacity:false) -Person_1.removevalueforkey ("Height") -println"person:\ (person) and person_1:\ (person_1) after deletion") the - //Remove key value pairs from the dictionaryWuyiLet Keysarr =[String] (Person_1.keys) theLet Valuesarr =[String] (person_1.values) -println"Keysarr: \ (Keysarr)") Wuprintln"Valuesarr: \ (Valuesarr)")
Run the output result:
A dictionary in Swift