Swift集合
程序=数据结构+算法 数据结构: 数组(array),栈(stack),队列(queue),链表(linked list),树(tree),图(graph),堆(heap)和哈希表(hash) 不同的结构对应于不同的算法,有的考虑节省空间,有的考虑速度,提高运行速度往往是以牺牲空间为代价,与之相反。 1、数组集合 数组是一串有序相同类型的元素构成的集合,数组更关心是否有序,而对于重复则不关心; (1)数组声明与初始化 数组声明:var studentList1:Array<String> var studentList2:[String] 初始化:var studentList1:Array<String> =["张三",“李四”] var studentList2:[String] = [ "张三",“李四”] let studentList3:[String] = ["张三","李四"] var studentList4:[String] = [String]() NSArray: 类,引用类型 Array:结构体,值类型 (2)数组的修改 可变数组中的元素进行追加,删除,插入和替换等修改操作; 1、追加元素可以使用append方法或者+操作符; 2、插入元素可以使用insert方法实现; 3、删除元素可以使用removeAtIndex方法实现; 4、替换元素可以直接赋值; var studentList1:[String] = ["张三","李四"] println(studentList1) studentList1.append("王五") studentList1 +=["赵六","王八"] studentList1.insert("张飞",atIndext:studentList.count) let removeStudent = studentList.removeAtIndex(0) (3)数组遍历 可以使用for in循环遍历数组 for (index,value) in enumarate(studentList){ println("Item(index+1)(vaule)") }
2、字典集合 字典表示一种非常复杂,允许按照某个键来访问元素,字典是由2部分集合构成的,一个是键(key)的集合,一个是值(value)的集合,键集合不能有重复的,值集合可以有重复的。 (1)字典声明与初始化 声明: var studentDicationary:Dictionary<Int,String> varstudentDicationary:[Int:String] 初始化: var studentDicationary:Dictionary<Int,String> = [102:"张三",103:“李四”] var studentDictionary = [102:"张三",103:"李四"] letstudentDictionary = [102:"张三",103:"李四"] ar studentDictionary = Dictionary<Int,String>()调用构造方法 (2)字典的修改 可变字典中的元素进行追加,删除和替换等操作 1、追加元素 如果给不存在的键赋值,结果是在字典中追加一个新的键值对 2、删除元素可以使用字典的removeAtIndex方法实现, 2种方法: 一种是通过给键值赋值nil; 另一种是通过字典的removeValueForKey(key)方法删除,方法的返回值就是要删除的值 3、替换元素 两种方法: 一种是直接给存在的键赋值, 另一种是通过updateValue(forkey:)方法替换,方法的返回值就是要替换的值 studentList.updateValue("李四",forkey:102) (3)字典的遍历 字典的遍历也是字典的重要操作,遍历值的集合,也可以遍历键的集合,也可以同时遍历,通过for in循环遍历 获得所有键集合:keys属性 获得所有值jiehe:values属性 var studentList = [102:"张三",103:"李四"] for studentID in studentList.keys{} for studentName in studentList.values{} for (studentId,studentName) in studentList{} 3、集合的复制 集合在赋值或参数传递过程中会发生复制,Swift中的值类型和引用类型,值类型会发生复制,而引用类型不会发生。 (1)字典复制 在为字典赋值或参数传递的时候,字典总是发生复制行为,但是它的键和值是否发生复制要看数据的类型, (2)数组复制 数组与字典复制类似,在为数组赋值或者参数传递的时候,数组总会发生复制 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |