Swift相比于Objective-C又一个重要的优点,它对函数式编程提供了很好的支持,Swift提供了map、filter、reduce这三个高阶函数作为对容器的支持。
1.map 函数可以对数组的每一个元素进行处理
// 计算字符串的长度
let stringLength = ["Objective-C", "Swift"]
// $0代表数组中的每一个元素
stringLength.map{
return $0.characters.count
}
// 数组的每一个元素是相应的元祖
let controllerInfo: [(String, String, UIViewController.Type)] = [
("夺宝", "duobao", MainController.self),
("最新揭晓", "zuixin", CompletedActivityController.self),
("晒单", "shaidan", CommunityController.self),
("购物车", "gouwuche", ShoppingController.self),
("我的", "geren", MineController.self)
]
override func viewDidLoad() {
super.viewDidLoad()
// 通过map函数 获取每一个元祖
self.viewControllers = controllerInfo.map({ (title, img, viewController) -> UINavigationController in
let vc = viewController.init()
vc.tabBarItem.image = UIImage(named: img)
vc.tabBarItem.title = title
vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: Theme.themeColor], for: .selected)
return CommonNavController(rootViewController: vc)
})
}
2.flatMap 与 map 函数的不同处:
(1)flatMap返回后的数组中不存在nil,同时它会把Optional解包
let oneArray = ["name", "age", "height", ""]
let length = oneArray.map { $0 -> Int? in
let stringLength = $0.characters.count
guard stringLength > 0 else {return nil}
return length
}
legth // [4, 3, 6, nil]
let length = oneArray.flatMap { $0 -> Int? in
let stringLength = $0.characters.count
guard stringLength > 0 else { return nil}
return stringLength
}
length // [4, 3, 6]
3.filter 可以对数组中的元素按照某种规则进行一次过滤
let oneArray = ["name", "age", "height"]
// $0表示数组中的每一个元素
stringArray.filter{ $0 -> Void in
if $0.characters.count > 4 {
print($0)
// height
}
}
4 reduce:计算,可以对数组的元素进行计算
let p1 = [20,20,10]
// $0 代表计算的值 $1代表元素
let sum = p1.reduce(0) { $0+$1 }
print(sum) //50
网友评论