swift 的高阶函数的使用代码

 1 //: Playground - noun: a place where people can play
 2 
 3 import UIKit
 4 
 5 var str = "Hello, playground"
 6 
 7 /// 使用map函数,进行数组内部数据的转换,map中接受一个转换函数
 8 var array =  [1,2,3,4,5]
 9 var newArray = array.map({$0 * 2})
10 print(newArray)
11 
12 
13  /// 使用reduce 函数 求和
14 var sum = array.reduce(0, combine: +)
15 print(sum)
16 
17 
18 /// 使用 filter来验证tweet中是否包含选定的若干关键字中的一个
19 let words = ["Swift","iOS","cocoa","OSX","tvOS"]
20 let tweet = "This is an example tweet larking about Swift"
21 let valid = !words.filter({tweet.containsString($0)}).isEmpty
22 print(valid)
23 
24 let valid1 = words.contains(tweet.containsString)
25 print(valid1)
26 
27 let valid2 = tweet.characters.split(" ").lazy.map(String.init).contains(Set(words).contains)
28 print(valid2)
29 
30 
31  /// 使用split map 分隔内容
32 let text = "窗前明月光 疑是地上霜 举头望明月 低头思故乡"
33 let lines = text.characters.split(" ").map(String.init)
34 print(lines[0])
35 print(lines[1])
36 print(lines[2])
37 print(lines[3])
38 
39 
40 /// 使用forEach 高阶函数便利
41 let name = "urai"
42 (1...4).forEach({print("Happy Birthday " + (($0 == 3) ? "dear (name)":"to You"))})
43 (1...4).forEach{print("Happy Birthday " + (($0 == 3) ? "dear (name)":"to You"))}
44 
45 
46 // MARK: - 查找数组中符合条件的数据
47 extension SequenceType {
48     
49     typealias Element = Self.Generator.Element
50     
51     func partitionBy(fu: (Element) -> Bool) -> ([Element],[Element]) {
52         
53         var first = [Element]()
54         var second = [Element]()
55         
56         for el in self {
57             
58             if fu(el) {
59                 
60                 first.append(el)
61             }
62             else {
63                 
64                 second.append(el)
65             }
66         }
67         return (first,second)
68     }
69 }
70 
71 let part = [82, 58, 76, 49, 88, 90].partitionBy{$0 < 60}
72 print(part)
73 
74 // MARK: - 一种更简介的查找方式
75 extension SequenceType {
76     
77     func anotherpartitionBy(fu: (Self.Generator.Element) -> Bool) -> ([Self.Generator.Element],[Self.Generator.Element]) {
78         
79         return (self.filter(fu),self.filter({!fu($0)}))
80     }
81 }
82 
83 let part1 = [82, 58, 76, 49, 88, 90].anotherpartitionBy{$0 < 60}
84 print(part1)
85 
86 /// 使用的是分区元组,但效率不如上边的高
87 var part2 = [82, 58, 76, 49, 88, 90].reduce( ([],[]), combine: {
88     (a:([Int],[Int]),n:Int) -> ([Int],[Int]) in
89     (n<60) ? (a.0+[n],a.1) : (a.0,a.1+[n])
90 })
91 print(part2)

代码

原文地址:https://www.cnblogs.com/machao/p/5446440.html