初识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])");
}
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...