Swift 数组使用有序列表存储 同一类型 的多个值,这点相对于Objective-C是有所不同的,OC中同一个数组,可以存放不同类型的元素。Swift 数组会强制检测元素的类型,如果类型不同则会报错。
数组初始化
创建空数组
//下面4种方式创建的空数组是等价的
var emptyArray : [Int] = []
var emptyArray : Array = []
var emptyArray = [Int]()
var emptyArray = Array()
创建有默认值的数组
下面的两个例子各创建了一个类型为Int,数量为5,初始值为0的数组
var allZeros = Array(repeating: 0, count: 5) //[0, 0, 0, 0, 0]
var allZeros = [Int](repeating: 0, count: 5) //[0, 0, 0, 0, 0]
创建一个含有4个元素的Int类型的数组
var numbers:[Int] = [0, 2, 4, 5]
//[Int]可以省去,系统能够检测出数组的类型
var numbers = [0, 2, 4, 5]
数组的增删改查
var letters = ["D", "B", "E", "A", "P", "F"] //如果是let,则不可修改
//获取长度
letters.count //6
//判空
letters.isEmpty //false
//元素获取
var str: String = letters[2] //"E"
letters.first //返回值为可选型String?
letters.last //同上
//最大值&最小值
letters.max() //"P"
letters.min() //"A"
//范围
letters[1..<3] //["B", "E"]
//包含关系
letters.contains("A") //true
letters.contains("M") //false
//获取索引
letters.index(of: "P") //4 类型为Int?
letters.index(after: 2) //3
//遍历
for index in 0..
二维数组
二维数组的定义
var board = [ [1024,16,2,0] , [256,4,2,0] , [64,2,0,0] , [2,0,0,0] ]
var board:[[Int]] = [ [1024,16,2,0] , [256,4,2,0] , [64,2,0,0] , [2,0,0,0] ]
var board:[Array] = = [ [1024,16,2,0] , [256,4,2,0] , [64,2,0,0] , [2,0,0,0] ]
var board:Array<[Int]> = [ [1024,16,2,0] , [256,4,2,0] , [64,2,0,0] , [2,0,0,0] ]
var board:Array> = [ [1024,16,2,0] , [256,4,2,0] , [64,2,0,0] , [2,0,0,0] ]
元素获取
board[0] //[1024,16,2,0]
board[0][0] //1024
两个维度的信息
board.count //4
board[0].count //4
二维数组每个维度的元素数量可以不等
board[1].append(4) //[[1024, 16, 2, 0], [256, 4, 2, 0, 4], [64, 2, 0, 0], [2, 0, 0, 0]]
board.append([1,2,3,4]) //[[1024, 16, 2, 0], [256, 4, 2, 0, 4], [64, 2, 0, 0], [2, 0, 0, 0], [1, 2, 3, 4]]