Swift 3.0 集合类型

来源:互联网 发布:3大云计算股票龙头股 编辑:程序博客网 时间:2024/06/06 00:43

Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。
数组、集合、字典的可变性,取决于 将其声明 为 var 或者 let。
数组(Arrays)是有序数据的集。
集合(Sets)是无序无重复数据的集。
字典(Dictionaries)是无序的键值对的集。

一、数组(Array)

数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中

1、创建

// 我们可以使用构造语法来创建一个由特定数据类型构成的空数组,通过构造函数的类型,someInts的值类型被推断为[Int]。var arrays = [Int]();print("arrays is type [Int] with \(arrays.count) items");// arrays is type [Int] with 0 items// 赋值arrays.append(3)print(arrays);//[3]//赋值为空arrays = [];print(arrays);// []// 创建一个带有默认值的数组:  threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]var threeDoubles = Array(repeating: 0.0, count: 3);//var threeDoubles:Array<Double> = Array(repeating: 0.0, count: 3);print(threeDoubles);//[0.0, 0.0, 0.0]//两个数组相加创建一个新数组var anotherThreeDoubles = Array(repeating: 2.5, count: 3);//sixDoubles 被推断为 [Double]var sixDoubles = threeDoubles + anotherThreeDoubles;print(sixDoubles);//[0.0, 0.0, 0.0, 2.5, 2.5, 2.5]//通过字面量构造数组var shoppingList = ["eggs","milk"];// var shoppingList:[String] = ["eggs","milk"];print(shoppingList);// ["eggs", "milk"]

2、访问数组
跟OC一致,通过数组的下标去访问数组。

//2.1 数组的元素个数var shoppingList = ["eggs","milk"];print("shoppingList has \(shoppingList.count) items");//shoppingList has 2 items// 2.2 数组是否为空if !shoppingList.isEmpty{    print("不为空");}// 不为空// 2.3 通过下标访问数组print(shoppingList[0]);//eggs

3、操作数组

var shoppingList = ["eggs","milk"];// 3.1 往数组后追加元素shoppingList.append("vegetable");print(shoppingList);//["eggs", "milk", "vegetable"]// 批量追加shoppingList += ["finsh"];print(shoppingList);//["eggs", "milk", "vegetable", "finsh"]// 3.2 插入//单个插入shoppingList.insert("noodles", at: 0);print(shoppingList);//["noodles", "eggs", "milk", "vegetable", "finsh"]//批量插入shoppingList.insert(contentsOf: ["A","y"], at: 0);print(shoppingList);//["A", "y", "noodles", "eggs", "milk", "vegetable", "finsh"]//3.3 修改//单个修改(替换)shoppingList[0] = "Apple";print(shoppingList);//["Apple", "y", "noodles", "eggs", "milk", "vegetable", "finsh"]// 批量修改shoppingList[1...2] = ["orange","pineapple"];print(shoppingList);//["Apple", "orange", "pineapple", "eggs", "milk", "vegetable", "finsh"]// 3.4移除// 移除最后一个shoppingList.removeLast();print(shoppingList);//["Apple", "orange", "pineapple", "eggs", "milk", "vegetable"]//移除第一个shoppingList.removeFirst();print(shoppingList);//["orange", "pineapple", "eggs", "milk", "vegetable"]//指定位置移除shoppingList.remove(at: 2);print(shoppingList);//["orange", "pineapple", "milk", "vegetable"]// 范围移除//shoppingList.removeSubrange(0...2);//print(shoppingList);//["egges"]// 移除全部//shoppingList.removeAll();//print(shoppingList);//[]//快速遍历数组for item in shoppingList{    print(item)}/*orangepineapplemilkvegetable*///果我们同时需要每个数据项的值和索引值,可以使用enumerated()方法来进行数组遍历。enumerated()返回一个由每一个数据项索引值和数据值组成的元组。for (index,value) in shoppingList.enumerated(){    print("\(index) -> \(value)");}/*0 -> orange1 -> pineapple2 -> milk3 -> vegetable*/

二、字典(Dictionary)

字典是一种存储多个相同类型的值的容器。每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。和数组中的数据项不同,字典中的数据项并没有具体顺序

1、创建

//创建 空字典  键是字符串类型,Any 表示值是任意类型var dictionary = [String:Any]();//使用字面量创建字典var dict:[String:Any] = ["name":"jack","age":23];print(dict);// ["name": "jack", "age": 23]

2、访问字典

var dict:[String:Any] = ["name":"jack","age":23];print("the dict has \(dict.count) key-value");//the dict has 2 key-value//判断字典是否为空if !dict.isEmpty{    print("字典不为空");}//字典不为空//遍历 键值对for (key,value) in dict{    print("key:\(key) - > value:\(value)");}/*key:name - > value:jackkey:age - > value:23*///遍历所有键for key in dict.keys{    print(key);}/*nameage*///遍历所有值for value in dict.values{    print(value)}/*jack23*///如何通过键获取值,第一步,判断键是否存在,第二步,如果键存在,那么获取值 如果这个字典包含请求键所对应的值,下标会返回一个包含这个存在值的可选值,否则将返回nilif let Name = dict["name"]{    print(Name);}else{    print("不存在");}//如果我们 直接获取  dict["name"]  这样得到的是一个可选的值。

3、操作字典

添加和修改 :如果访问的键存在,那么即修改,如果不存在,即添加

var dict:[String:Any] = ["name":"jack","age":23];dict["sex"] = "男";dict["name"] = "tom";print(dict);// ["name": "tom", "age": 23, "sex": "男"]

移除

// (1)直接赋值成nildict["sex"] = nil;print(dict);// ["name": "tom", "age": 23]// (2) 移除if let removeValue = dict.removeValue(forKey: "name"){      print("The removed airport's name is \(removeValue).")}else{    print("The airports dictionary does not contain a value for Name.")}print(dict);//The removed airport's name is tom.//["age": 23]

三、集合
集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。Swift的Set类型被桥接到Foundation中的NSSet类。 因为集合没有确定顺序可言,所有对一个集合操作下标是没有意义的

1、创建集合

var sets = Set<String>();// 通过字面量(有字面量一般不需要给类型)创建集合var  fruitSets:Set = ["Apple","Orange"];//var  fruitSets:Set<String> = ["Apple","Orange"]; 

2、操作集合

添加

var  fruitSets:Set = ["Apple","Orange"];print("fruitSets has \(fruitSets.count) items");//fruitSets has 2 items// 添加元素fruitSets.insert("pineapple");print(fruitSets);// ["Orange", "Apple", "pineapple"]//判断集合是否包含特定值if fruitSets.contains("pineapple"){    print("fruitSets contain pineapple");}//fruitSets contain pineapple

删除: 你可以通过调用Set的remove(_:)方法去删除一个元素,如果该值是该Set的一个元素则删除该元素并且返回被删除的元素值,否则如果该Set不包含该值,则返回nil。

if let remove =  fruitSets.remove("ok"){    print("删除成功");}else{    print("删除失败,集合中没有这个值");}//  删除失败,集合中没有这个值//fruitSets.removeAll();//print(fruitSets);//[]//遍历一个集合 : Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,它将返回一个有序数组,这个数组的元素排列顺序由操作符'<'对元素进行比较的结果来确定。for (index,value) in fruitSets.sorted().enumerated(){    print("\(index) -> \(value)");}/*0 -> Apple1 -> Orange2 -> pineapple*/

集合间的关系

// 定义如下3个集合let a:Set<Int> = [1,3,5,7,9];let b:Set<Int> = [0,2,4,6,8];let c:Set<Int> = [2,3,5,7];// a 和 b 中 相同数的集合(交集)let d:Set = a.intersection(b);print(c);//  []// a + b  所有数相加的集合(并集)let e:Set = a.union(b);print(e.sorted());// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]//  a + c - (a和c共有的部分) 所组合的数的集合let f:Set = a.symmetricDifference(c);print(f.sorted());//[1, 2, 9]// a- (a和c共有的) 的数的集合let g:Set = a.subtracting(c);print(g.sorted());// [1,9]// 判断两个集合是否相等 ==// 包含let fruits:Set = ["orange","pineapple","apple"];let Orange:Set = ["orange"];let Peach:Set = ["peach"];if Orange.isSubset(of: fruits){    print("集合Orange的全部元素都在集合fruits中");}//集合Orange的全部元素都在集合fruits中if fruits.isSuperset(of: Orange){    print("集合Orange的全部元素都在集合fruits中");}//集合Orange的全部元素都在集合fruits中if fruits.isDisjoint(with: Peach){      print("集合fruit和集合Peach没有相同的元素");}//集合fruit和集合Peach没有相同的元素
0 0
原创粉丝点击