11.swift-Dictionary字典

2021-07-13  本文已影响0人  ChaosHeart

//: Playground - noun: a place where people can play

import UIKit

//字典的介绍
//字典运行按照某个键来访问元素
//字典是由两个部分集合构成,一个是键(key)集合,一个是值(value)集合
//键集合是不能有重复元素的,值集合是可以重复的,键和值是成对出现的
/*
 swift中的字典
   swift字典类型是Dictionary,也是一个泛集合
 */



//可变的字典:使用var修饰
var namesOfIntegers = [Int: String]();
// namesOfIntegers is an empty [Int: String] dictionary
namesOfIntegers[16] = "sixteen";
// namesOfIntegers now contains 1 key-value pair
//将字典清空
namesOfIntegers = [:];


//字典类型 String : String
//空字典
var diction = Dictionary<String,String>();
//空字典
var dict = [String : String]();
//备注类型写法
//var air : [String : String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
//字面量字典
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
//添加键值对
airports["LHR"] = "London";
//修改键值对
airports["LHR"] = "London Heathrow";
print(airports);


//字典类型 Int : String
//空字典
var dictionInt = Dictionary<Int,String>();
//空字典
var dictInt = [Int : String]();
//备注类型写法
//var airInt : [Int : String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
//字面量字典
var airportsInt = [1: "Toronto Pearson", 2: "Dublin"];
//添加键值对
airportsInt[3] = "London";
//修改键值对
airportsInt[3] = "London Heathrow";
print(airportsInt);


//字典类型 Int : Int
//空字典
var dictionIntInt = Dictionary<Int,Int>();
//空字典
var dictIntInt = [Int : Int]();
//备注类型写法
//var airInt : [Int : String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
//字面量字典
var airportsIntInt = [1: 2, 2: 2];
//添加键值对
airportsIntInt[3] = 3;
//修改键值对
airportsIntInt[3] = 4;
print(airportsIntInt);


//字典类型 String : Int
//空字典
var dictionStringInt = Dictionary<String,Int>();
//空字典
var dictStringInt = [String : Int]();
//备注类型写法
//var airInt : [Int : String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
//字面量字典
var airportsStringInt = ["1": 2, "2": 2];
//添加键值对
airportsStringInt["3"] = 3;
//修改键值对
airportsStringInt["3"] = 4;
print(airportsIntInt);


//字典类型 String:Any
var dic : [String : Any] = ["key":"value","name":"小明","age":15];
//可变的字典:使用var修饰
var dicAny = Dictionary<String,Any>();
//任何类型
var dictAny = [Int : Any]();
//修改已有的值
dic["name"] = "2";
//添加键值对
dic["sex"] = ["男","女"];
//输出
print(dic);
//删除指定单个键值对
dic.removeValue(forKey: "key");


//遍历字典(所有的键)
for key in dic.keys {
    print(key);
}
//遍历字典(所有的值)
for value in dic.values{
    print(value);
}

//遍历所有的键值对
for (key,value) in dic{
    print(key);
    print(value);
}


//字典的合并
//即使字典里的元素类型也不能相加进行合并
var dic1 = ["name":"why","age":1.88] as [String : Any];
var dic2 = ["age":18,"sex":"女"] as [String : Any];
for (key,value) in dic2{
    dic1[key] = value;
}

//删除所有
dic.removeAll();
//判断字典中是否有元素
//dic.isEmpty=0
if dic.isEmpty {
    //dic.isEmpty=0
    print("The airports dictionary is empty.")
} else {
//    dic.isEmpty!=0
    print("The airports dictionary is not empty.")
}


//字典类型 String:Any
var dddd = ["key":"value","name":"小明","age":15] as [String:Any];
for item in dddd {
    print("item: \(item)");
}


上一篇 下一篇

猜你喜欢

热点阅读