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