数组(Arrays)是有序数据的集,元素可重复;
遵守Array<Element>类型,Element是这个数组中唯一允许存在的数据类型;
也可以用简单的形式表示:[Element]
1.定义
//空数组
var tempArr = Array<String>() //也可以
var arr = [String]()
//字面量赋值
var arr1 : [String] = ["a","b","c"]
var arr2 = ["a","b","c","d"]
var arr3 = Array(repeating: "0", count: 5)
2.数组是否为空
/*
var arr = [String]()
if arr.isEmpty {
print("arr is empty")
}
//arr is empty
*/
3.数组的长度:count
4.数组的访问:下标法
var arr2 = ["a","b","c","d"]
print(arr2[2]) //c
5.增
var arr2 = ["a","b","c","d"]
var arr3 = arr2
//增加单个元素
arr2.append("f")
//增加数组
arr2 += ["1","2"]
print(arr2) // ["a", "b", "c", "d", "f", "1", "2"]
arr3.insert("_", at: 0)
print(arr3) // ["_", "a", "b", "c", "d"]
6.删
//tempArr.removeAll() //清空全部数组
//tempArr.removeLast() //删除第一个元素
//tempArr.removeFirst()//删除第一个元素
//tempArr.removeFirst(n: Int) param:n: Int代表第几个元素;n = 1,表示删除tempArr[0]
var arr2 = ["a","b","c","d"]
arr2.remove(at: 1)
print(a) // ["a", "c", "d"]
7.改
var arr2 = ["a","b","c","d"]
//当个元素
arr2[0] = "1"
print(arr2) //["1", "b", "c", "d"]
//多个元素
arr2[1...2] = ["2","3"]
print(arr2) //["1", "2", "3", "d"]
8.数组的遍历
//forin 遍历 :获取元素
var arr2 = ["a","b","c","d"]
for item in arr2 {
print(item)
}
//a
//b
//c
//d
//enumerated()遍历,获取每个数据项的值和索引值
var arr2 = ["a","b","c","d"]
for (index,value) in arr2.enumerated() {
print("Item \(String(index)): \(value)")
}
//Item 0: a
//Item 1: b
//Item 2: c
//Item 3: d
网友评论