swift-字典

swift字典

  • 在swift中,key:key值必定是可hash的,必定是獨一無二的,swift的基本數據類型(String,Int,Float)都是可哈希的,因此均可以做爲key值。 value:沒有要求swift

  • 直接上代碼了,註釋給你們標的很明白code

    //建立字典並賦值
      let dict = ["name":"xiaoyu","age":12]
      let dict2:[String:Any] = ["name":"xiaoyu","age":12];
      let dict3:Dictionary<String,Any> = ["name":"xiaoyu","age":13,"height":130]
    
      print(dict3)
    
      //建立空字典
    
      let dict4:[String:Any] = [:]
      let dict5:[String:Any] = Dictionary()
    
      //建立可變字典
      var dict6:[String:Any] = ["name":"xiaoyu"]
    
      //更新字典的數據 value輸出的是原來的key對應的value值
      if let Value = dict6.updateValue("dayu", forKey: "name")
      {
          print(Value)
          print(dict6)
      }
    
      //刪除字典元素
      dict6.removeValueForKey("name")
      //刪除所有元素
      dict6.removeAll()
      dict6.removeAll(keepCapacity: true)
      //遍歷字典
      for (key,value) in dict6
      {
          print("key:\(key) value:\(value)")
      }
    
      for key in dict6.keys{
          print("key:\(key)")
      }
    
      //合併字典
    
      var dict7:[String:Any] = ["name":"小雨","age":133]
    
      var newDict8:[String:Any] = ["weight":"小於","height":13]
      for (key,value) in newDict8{
          dict7.updateValue(value, forKey: key)
      }
    
      print("dict7:\(dict7)");
相關文章
相關標籤/搜索