数组定义
数组要明确类型
- 1. 声明出来 Array<Int>
- 2. 推断出来 let array3 = [1,2,3]
let array1: Array<Int> = []
let array2: Array = [1,2,3]
let array0:[Int] = []
let array3 = [1,2,3]
let array4 = Array<Int>.init()
let array5 = Array<Int>()
- 遍历数组 array.map
let array = [1,2,3,4]
// func map<T>(_ transform: (Element) throws -> T) rethrows -> [T]
// 方法返回数组, 接受一个闭包参数, 参数闭包, 接收当前数组元素, 返回新表达式生成的数组元素
let array1 = array.map { (item: Int) -> Int in
item * 2 // { $0 * 2 }
}
print(array1) // [2, 4, 6, 8]
// int元素转字符串
let array11 = array.map { item in
"\(item)"
}
print(array11) // ["1", "2", "3", "4"]
// 1 遍历数组, 字符串元素转Int
let arr = ["123", "test", "jack", "-30"]
var arr2 = arr.map { Int($0) }
print(arr2) // [Optional(123), nil, nil, Optional(-30)] // 结果为可选
// 2 缩进数组
var arr3 = arr.compactMap { Int($0) }
print(arr3) // [123, -30] // 结果为Int
// 3 拼接数组
var arr = [1, 2, 3]
// [[1], [2, 2], [3, 3, 3]]
var arr2 = arr.map { Array.init(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3]
var arr3 = arr.flatMap { Array.init(repeating: $0, count: $0)}
- 过滤数组 array.filter
// func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element]
// 方法返回数组, 接收闭包参数, 闭包接收数组元素, 表达式返回Yes的元素, 放进返回数组
let array2 = array.filter { item in
item / 2 == 0 // { $0 / 2 }
}
print(array2) // [1]
- 遍历带参数保存结果 array.reduce
// func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
// 方法返回 result类型, 闭包参数返回表达式结果及 数组下一个元素 返回result类型
// reduce: 初始值
// initialResult: 当前表达式计算结果
// nextPartialResult: 下一个元素
表达式计算结果通过 partialResult 代表当前表达式结果
let array3 = array.reduce(1) { (partialResult, Element) -> Int in
return partialResult + Element // { $0 + $1 }
}
print(array3) // 11
- 数组遵守了equalable协议 可以做加法
let array = [1] + [1,2]
print(array) // [1, 1, 2]
- 遍历数组 array.forEach
let allStudents: [Int] = [1,2,3,4,5,6]
let res6 = allStudents.forEach { num in
print(num) // 1, 2, 3, 4, 5, 6
}
- 数组排序 array.sorted
// func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]
// 方法返回数组, 传入闭包参数, 闭包有两个参数 返回表达式 Bool 值
let array = [9,5,7,3,4,6,2]
let array1 = array.sorted { num0, num1 in
num0 > num1
}
print(array,array1)
// [9, 5, 7, 3, 4, 6, 2] [9, 7, 6, 5, 4, 3, 2]