初识Swift集合之数组集合
数组集合 基础操作: 数组集合定义:由一串有序的相同类型的元素构成的集合 数组的基本声明: 1、 var strudentList : Array<Int> ; //声明一个strudentList 数组,数组元素的类型是Int型 2、var strudentList : [Int] ; //一种偷懒的strudent List数组声明,数组元素类型是Int 型 数组的初始化 1、var strudentList : Array<Int>= [10,10,10] //声明初始化studentList 型 2、var strudentList = [10,101] //根据Swift语言的类型推断能力来声明一个studentList的数组,数组元素类型是 Int 型。 3、var strudentList = Array<Int>() //声明一个空值的strudentList数组,数组元素的类型是Int型 4、var strudentList = [String]() // 声明一个控制的strudentList 数组,数组元素类型是String型 在声明数组的时候我们可以使用两个关键字 var和let ,在使用var 的时候,程序后期可以改变数组的值;在使用let 的时候,数组已经声明之后不能发生改变 数组元素操作:增、删、改、插入元素 增加元素 例子:var strudentList : Array<String> = ["张三","Jack"] ; 1、在数组末尾添加一个元素 strudentList.append("十元") ; 2、在数组末尾添加多个元素 strudentList += ["Mark","R"] ; 插入元素 strudentList.insert("飞鱼",atIndex : num) //num是要插入的数组位置,这里请注意数组的位置时从零开始计算的,比如[10,10] 那么他的下表技术为 0,1 删除元素 let names=strudentList.removeAtIndex(num) ; //num是要删除数组元素的下表,使用这种删除方法,方法可以返回被删除元素的内容,如果不需要这个元素我们可以直接strudentList.removeAtIndex(num) 数组的遍历 数组的遍历啊有三种方法可以使用 1、for in 输出数组元素 foriteminstudentList{ println(item); } 2、输出数组下标和元素 for(id,name)inenumerate(studentList){ if(id!=studentList.count-1){ print("Item(id):(name),"); }else{ println("Item(id):(name)"); } } 3、使用这种方法输出 for(vari:Int=0;i<strudentList.count-1;i++){ if(i!=strudentList.count-2){ print("Item(i):(strudentList[i]),"); }else{ println("Item(i):(strudentList[i])"); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |