Swift函数式编程,函数式编程的思想就是一切皆函数,可以是被当作变量,参数,返回值。高阶函数运用对swift编程很重要。
基础一般常用的几个高阶函数如下
let numArr = [5, 4, 6, 1, 7]
//遍历所有并操作
print(numArr.map{$0 + 1}) //输出:[6, 5, 7, 2, 8]
//遍历所有按照条件筛选
print(numArr.filter{$0 > 5}) //输出:[6, 7]
//遍历后合并处理结果
print(numArr.reduce(100) {$0 + $1}) //输出123
//过滤空值
let strArr = ["nihao", "iOS", nil, "haha"]
let validStrArr = strArr.compactMap{$0}
print(validStrArr) //输出["nihao", "iOS", "haha"]
//打印字符长度
let counts = strArr.compactMap{$0?.count}
print(counts) //输出[5, 3, 4]
//集合合并
let results = [[1, 2, 3],[2, 3, 4],[4, 5, 6]]
let allResults = results.flatMap{$0.map{$0 * 10}}
print(allResults) //输出[10, 20, 30, 20, 30, 40, 40, 50, 60]
//合并后过滤
let passResults = results.flatMap{$0.filter{$0 > 4}}
print(passResults) //输出[5, 6]
我们主要看函数式编程和oc中命令式编程的对比。在面向对象的命令式编程语言里面,重用的单元是类和类之间沟通用的消息。函数式编程语言实现重用的思路很不一样。函数式语言提倡在有限的几种关键数据结构(如list、set、map)上运用针对这些数据结构高度优化过的操作,以此构成基本的运转机构。开发者再根据具体用途,插入自己的数据结构和高阶函数去调整机构的运转方式。函数式编程用map()、filter()这些高阶函数把我们解放出来,让我们站在更高的抽象层次上去考虑问题,把问题看得更清楚。
我们看两个例子
let NON_WORDS = ["a", "of", "and", "the", "on"]
let str = "Parameter transform: A mapping closuretransform acceptsan element of this sequence as its parameter and returns a transformed value of the same or of a different type. Returns: An array containing the transformed elements of thissequence"
//命令式编程,遍历单词出现次数
func wordFreq (words: String) -> [String:Int] {
var wordsDic: [String : Int] = [:]
let wordsArr = words.split(separator: " ")
for word in wordsArr {
let lowerWord = word.lowercased(); //转小写
if !NON_WORDS.contains(lowerWord) { //剔除不需要记录的单词
if let cont = wordsDic[lowerWord] {
wordsDic[lowerWord] = cont + 1 //再次出现 +1
}else {
wordsDic[lowerWord] = 1 //首次出现
}
}
}
return wordsDic
}
print(wordFreq(words: str))
//函数式编程,遍历单词出现次数
func wordFreq2 (words: String) -> [String : Int] {
var wordDic : [String : Int] = [:]
let wordsArr = words.split(separator: " ")
wordsArr.map{$0.lowercased()} //对数组中所有字符参数进行消息操作
.filter{!NON_WORDS.contains($0)} //判断每个字符是否是不需要统计的字符,如果不是则进行下一步操作
.forEach {wordDic[$0] = (wordDic[$0] ?? 0) + 1} //遍历所有字符元素,使用合并空值对出现次数进行++
return wordDic
}
print(wordFreq2(words: str))
//命令式编程,剔除单个字符
let enployee = ["iOS", "s", "hello", "word", "m"]
func cleanName(word: [String]) -> String {
var name = ""
for word in enployee {
if word.count > 1 {
name += word.capitalized + "," // 首字母大写,尾部添加,
}
}
return name;
}
//函数式编程,剔除单个字符
let result = enployee.filter{$0.count > 1} //删掉字符为1个数的字符
.map{$0.capitalized} //首字母进行大写
.joined(separator: ",") //添加尾部,
print(cleanName(word: enployee))
print(result)