美文网首页
swift字典

swift字典

作者: 星辰流转轮回 | 来源:发表于2016-06-01 17:37 被阅读36次

    //声明字典

    //空字典
    let dic = [:]

    print(dic)
    //限定键值类型的空字典 key为string类型 value
    var dic1 = Dictionary<String,Float>()
    var dic2:Dictionary = ["1":111,"2":222]
    var dic3:[String:Int] = ["1":111]

    print(dic1, dic2 ,dic3)

    var newDic = ["key":"value","朕":"本帝"]
    print(newDic)
    //查询
    var theValue = newDic["key"]
    print(theValue)
    //增加/修改
    //查找字典,若原字典有这个key,则更改对应的value;若无,则添加一对新的键值对
    newDic["key"] = "newValue"
    print(newDic)
    newDic["you"] = "zha5"
    print(newDic)

    newDic.updateValue("shui", forKey: "shen")
    print(newDic)

    //如果原字典没有这个key,会返回一个nil,并添加进去,如果存在,返回value
    if let isnil = newDic.updateValue("nil", forKey:"buzai") {
    print(isnil)
    }else{
    // print(isnil)
    print("原来不存在")
    }

    print(newDic)

    //删除

    newDic["buzai"] = nil
    print("删除了"buzai 后----(newDic)")

    //如果key存在删除对应的键值对并返回key对应的值,不存在key返回nil字典不变
    if let value = newDic.removeValueForKey("shen") {
    print(value)
    print("yes--(newDic)")

    }else{
    print("no--(newDic)")

    }
    //字典的元素个数
    print(newDic.count)
    print(String(newDic.count))

    //遍历字典
    for (key,value) in newDic{
    print("(key):(value)")
    }
    //遍历所有的key
    for key in newDic.keys{
    print(key)
    print(newDic[key])
    }
    //遍历所有的value
    for value in newDic.values{
    print(value)
    }

    let allKeys = Array(newDic.keys)
    let allValue = newDic.values
    print(allKeys)
    print(allValue)

    相关文章

      网友评论

          本文标题:swift字典

          本文链接:https://www.haomeiwen.com/subject/rvvhdttx.html