swift 字典NSDictionary的定義,修改索引值,刪除/添加索引值

來源:互聯網
上載者:User
// Playground - noun: a place where people can playimport UIKit//------------------------------------------------------------------------------// 1. 定義固定格式的字典// dict1的所有“索引值”類型一致(都是字串)var dict1 = ["name": "mary", "age": "18"]//------------------------------------------------------------------------------// 2. 在定義字典是可以直接指定字典中"鍵名"和"索引值"的類型//    一旦指定了字典的鍵名和索引值類型,則不能再修改var ages: Dictionary<String, Int> = ["jack": 20, "rose": 19]//------------------------------------------------------------------------------// 3. 字典操作//    對于格式固定的字典是可以直接操作的// 1> 用索引值擷取字典索引值,由於字典格式固定,因此無需在指定變數類型// *** 注意"指定/取消"取實值型別指定的運行結果是不同的var name = dict1["name"] // as Stringname = "mike " + "\(name)"// *** 由於從字典擷取數值時,可能會得到一個nil,因此如果需要對資料做後續處理,需要判斷一下if var age = dict1["age"]?.toInt() {    age += 20}// 2> 修改字典索引值的兩種方法dict1["name"] = "rose"dict1dict1.updateValue("18", forKey: "age")dict1// 3> 刪除某一個索引值dict1.removeValueForKey("age")dict1// 4> 添加新的索引值對dict1["height"] = "1.65"dict1

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.