map filter reduce
class HomeViewController: UIViewController {
func double(_ i : Int) -> Int {
i * 2
}
override func viewDidLoad() {
super.viewDidLoad()
let arr = [1,2,3,4]
//将数组arrd里面的元素 做转换
//每个元素乘以2,返回一个数组
let arr2 = arr.map { $0 * 2 }
print(arr2)
//将数组arr里面的元素过滤
//过滤里面们备2乘除的元素,返回一个数组
let arr3 = arr.filter { $0 % 2 == 0
}
print(arr3)
//遍历数组arr中的元素
//将数组中的每个元素和0相加,并报错这个结果
//用于和数组中下一个元素相加
//实现 在初始值为A情况 累加数组中元素的效果
let arr4 = arr.reduce(0) { (result, element) -> Int in
return result + element
}
print(arr4)
//与上面写法等价
let arr5 = arr.reduce(0, +)
print(arr5)
//map函数作用:便利数组中的每一个元素,
//每次将数组中便利到的元素作为参数
//传到double 函数中,与
//arr.map { $0 * 2 }等价
print(arr.map(double))
}
}
flatMap
let arr = [1,2,3,4]
//arr.map 遍历每一个元素,并将每次遍历
//到的元素作为参数传递给闭包即为:$0
//Array.init(repeating:, count:)
//Array使用元素$0重复创建数组元素.
//重复次数为$0
let arr2 = arr.map {
Array.init(repeating: $0, count: $0)
}
//[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
print(arr2)
//将多为数组展开成以为数组
let arr3 = arr.flatMap { Array.init(repeating: $0, count: $0)
}
//[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
print(arr3)
compactMap
let arr = ["123","test","jack","-30"]
//遍历数组arr,取出每个元素,使用Int构造函数
//返回一个Int元素.Int构造函数返回值为
//Optional
let arr2 = arr.map { Int($0) }
//[Optional(123), nil, nil, Optional(-30)]
print(arr2)
let arr3 = arr.compactMap {
Int($0)
}
//[123, -30]
print(arr3)
使用reduce实现map和filter的功能
let arr = [1,2,3,4]
print(arr.map { $0 * 2 })
print(arr.reduce([]) {
$0 + [$1 * 2]
})
print(arr.filter{ $0 % 2 == 0 })
print(arr.reduce([]) { $1 % 2 == 0 ? $0 + [$1] : $0 })
let arr1 = [1,2]
let arr2 = [3] + [4]
print(arr1 + arr2)
lazy的优化
let arr = [1,2,3,4]
//注意添加了lazy关键字
let result = arr.lazy.map { (elelment) -> Int in
print("mapping \(elelment)")
return elelment * 2
}
print("begin")
print("mapped",result[0])
print("mapped",result[1])
print("mapped",result[2])
print("end")
//打印结果
begin
mapping 1
mapped 2
mapping 2
mapped 4
mapping 3
mapped 6
end
- 无
lazy
优化
可以看到,在访问result
之前,map
操作已经完成.而添加了lazy
关键字,可以看到:
let arr = [1,2,3,4]
let result = arr.map { (elelment) -> Int in
print("mapping \(elelment)")
return elelment * 2
}
print("begin")
print("mapped",result[0])
print("end")
//打印结果
mapping 1
mapping 2
mapping 3
mapping 4
begin
mapped 2
end
Optional的map和faltMap
let num1: Int? = 10//Optional(20)
let num2 = num1.map { $0 * 2 }
print(num2)//Optional(20)
let num3: Int? = nil
let num4 = num3.map { $0 * 2 }
print(num4)//nil
let num1: Int? = 10
let num2 = num1.map {
Optional.some($0 * 2)
}
print(num2)//Optional(Optional(20))
let num3 = num1.flatMap {
Optional.some($0 * 2)
}
//会将多层Optional展平
print(num3)//Optional(20)
let num1: Int? = 10
let num2 = (num1 != nil) ? (num1! + 10) : nil
let num3 = num1.map { $0 + 10 }
print(num3)
print(num2)
override func viewDidLoad() {
super.viewDidLoad()
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
let str: String? = "2011-09-10"
let date1 = str != nil ? fmt.date(from: str!) : nil
print(date1)
let date2 = str.flatMap(fmt.date)
print(date2)
let date3 = str.flatMap { (string) -> Date? in
print(string)
return fmt.date(from: string)
}
print(date3)
let date4 = str.flatMap {
fmt.date(from: $0)
}
print(date4)
//打印结果都为:
//Optional(2011-09-09 16:00:00 +0000)
}
override func viewDidLoad() {
super.viewDidLoad()
let score: Int? = 98
let str1 = score != nil ? "score is \(score!)" : "NO score"
let str2 = score.map {
"score is \($0)"
} ?? "No score"
print(str1)
print(str2)
//score is 98
}
import UIKit
struct Person {
var name: String
var age: Int
}
class HomeViewController: UIViewController {
let items = [
Person(name: "jack", age: 20),
Person(name: "rose", age: 21),
Person(name: "kate", age: 22)
]
override func viewDidLoad() {
super.viewDidLoad()
print(getPerson1("ro1se"))
print(getPerson2("rose"))
}
func getPerson1(_ name: String) -> Person? {
let index = items.firstIndex { (person) -> Bool in
person.name == name
}
return index != nil ? items[index!] : nil
}
func getPerson11(_ name: String) -> Person? {
let index = items.firstIndex { $0.name == name
}
return index != nil ? items[index!] : nil
}
func getPerson2(_ name: String) -> Person? {
return items.firstIndex { (person) -> Bool in
person.name == name
}.map { (index) -> Person in
items[index]
}
}
func getPerson22(_ name: String) -> Person? {
items.firstIndex { $0.name == name }.map {
items[$0]
}
}
}
let json: Dictionary? = ["name": "jack", "age": 11]
let p1 = json != nil ? Person(json!) : nil
let p2 = json.flatMap(Person.init)
json?.compactMap {
print($0)
print($1)
print("yyyy")
}
//打印结果
age
11
yyyy
name
jack
yyyy