数组
创建数组
swift
let names = ["mondo", "imondo.cn"];
let ages:[Int] = [32, 33];
let arr:[Any] = [1, "Mondo"];
let arr1:Array<AnyObject> = [1, "2"];
var test = [Int]();
var someInts = [Int](repeating: 0, count: 3); // 初始值为 0,数量为 3 的 Int 类型数组
操作数组
swift
var arr:[Any] = [1, "2", 3];
// 访问
arr[2] // 下标 2 的元素
// 新增
arr.append("Mondo"); // 最后位置新增
arr += ["imondo.cn", 55]; // [1, "2", 3, "imondo.cn", 55]
arr.insert("two", at: 1); // 指定位置添加,at 参数范围不能操作数组长度
// 移除
arr.removeLast(); // 删除最后一个元素
arr.removeFirst(); // 删除第一个元素
arr.remove(at: 1); // 删除指定位置元素
// 合并数组
var a:[Int] = [1, 2, 3]
var b:[Int] = [4, 5]
var c = a + b // 合并
遍历数组
普通遍历
swift
let testArray = [1, 2, 3, 4, 5]
for value in testArray {
print(value)
}
// 1, 2, 3, 4, 5
- 遍历的时候,同时获得索引和值。使用
enumerated
方法
swift
let testArray = [1, 2, 3, 4, 5]
for (index, value) in testArray.enumerated() {
print("\(index): \(value)")
}
// 0: 1
// 1: 2
// ...
// 4: 5
通过闭包 closure
遍历
swift
let testArray = [1, 2, 3, 4, 5]
testArray.forEach {(value) in
print(value)
}
高级函数遍历数组
- map
swift
let arr = [1, 2, 3, 4, 5]
let a = arr.map {
return $0 + 2
}
- flatMap
flatMap
遍历时会把二维数组变为一维数组
- compactMap
遍历数组时,会把 nil
值去除
swift
let testList = [1, 2, 2, 3, 3, 4, nil, 5, 6]
let lsArray: [Int] = testList.compactMap { (num) -> Int? in
return num
}
// [1, 2, 2, 3, 3, 4, 5, 6]
- filter
swift
let arr = [1, 2, 3, 4, 5]
let a = arr.filter {
return $0 > 3
}
- min 、 max
返回最小,最大值
swift
let testList = [1, 2, 2, 3, 3, 4, 5, 6]
testList.min() // 1
testList.max() // 6
- sorted 和 partition
swift
let mixArray = finallyArray.sorted() // [52, 63, 70, 73, 83, 84, 85, 86, 89, 96, 99, 100]
let maxArray = finallyArray.sorted(by: >) // [100, 99, 96, 89, 86, 85, 84, 83, 73, 70, 63, 52]
- 判断两个数组是否相等
elementsEqual
方法
swift
var z = [1, 2]
var x = [1, 3]
var isTrue = z.elementsEqual(x, by: {
$0 == $1
})
print("\(isTrue)") // false
- 数组是否是以特定的排序开头
swift
var z = [1, 2]
z.starts(with: [1], by: {
$0 == $1
}) // true
- 计算数组中元素和
swift
var x = [1, 2]
var xx = x.reduce(0, +)
print("\(xx)") // 3
reduce
函数使用方法
swift
let names = ["alan", "brian", "charlie"]
let scv = names.reduce(into:[]) { arr, v in
arr.append(v)
}
print("\(scv)") // ["alan", "brian", "charlie"]
- 按条件把数组中的元素分类
swift
let pass = mixArray.partition(by: {
$0 > 60
})
let failedArray = mixArray[0 ..< pass] // 不及格的 [52]
let passArray = mixArray[pass ..< mixArray.endIndex] // 及格的 [63, 70, 73, 83, 84, 85, 86, 89, 96, 99, 100]
count 和 isEmpty
count
属性返回数组长度
swift
let testArray = ["one","two","three","four","five","six"]
let countInts = testArray.count // 6
isEmpty
属性判断数组是否为空,返回布尔值
swift
var ary:[Int] = [1, 3];
print("\(ary.isEmpty)")