美文网首页Swift5iOS
Swift5 字典(Dictionary)操作

Swift5 字典(Dictionary)操作

作者: 圣艾修 | 来源:发表于2020-03-25 11:35 被阅读0次

    Swift字典创建

    let dic : Dictionary<String, Any> = [:]
    let dic1 : [String : Any] = [:]
    let dic2 = ["name": "Alice", "age": 10] as [String : Any]
    print(dic, dic1, dic2)
    // 结果:[:] [:] ["age": 10, "name": "Alice"]
    

    Swift字典判空

    let dic : Dictionary<String, Any> = [:]
    print(dic.isEmpty)
    //结果:true
    
    

    Swift字典键值对个数

    let dic : Dictionary<String, Any> = ["name":"Alice", "age": 22]
    print(dic.count)
    // 结果:2
    
    

    Swift字典所有键值对

    let dic : Dictionary<String, Any> = ["name":"Alice", "age": 22]
    print(dic.keys, dic.values)
    // 结果:["age", "name"] [22, "Alice"]
    

    Swift字典取值

    let dic : Dictionary<String, Any> = ["name":"Alice", "age": 22]
     print(dic["age"]!,dic["notExist"])
     // 结果:22 nil
    

    Swift字典元素增删改

    var dic : Dictionary<String, Any> = ["name":"Alice", "age": 22]
    dic.updateValue(21, forKey: "age")
    print(dic)
    // 结果: ["age": 21, "name": "Alice"]
    
    dic["gender"] = "male"
    print(dic)
    // 结果:["name": "Alice", "age": 21, "gender": "male"]
    
    dic.removeValue(forKey: "name")
     print(dic)
    // 结果:["gender": "male", "age": 21]
            
    

    Swift字典遍历

    let dic : Dictionary<String, Any> = ["name":"Alice", "age": 22]
    for obj in dic {
        print(obj.key, obj.value)
    }
    // 结果:name Alice age 22
    

    Swift5 字符串(String)操作
    Swift5 字符(Character)操作
    Swift5 数组(Array)操作
    Swift5 字典(Dictionary)操作
    Swift5 集合(Set)操作
    Swift5 简单使用
    Swift OC动态调试工具 InjectionIII 使用

    相关文章

      网友评论

        本文标题:Swift5 字典(Dictionary)操作

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