swift-字典

swift字典

  • 在swift中,key:key值一定是可hash的,一定是独一无二的,swift的基本数据类型(String,Int,Float)都是可哈希的,所以都可以作为key值。 value:没有要求

  • 直接上代码了,注释给大家标的很明白

      //创建字典并赋值
      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)");
posted @ 2016-09-14 15:50  往事亦如风  阅读(...)  评论(... 编辑 收藏