
函数式编程的核心是函数,函数是“头等公民”。这就像面向对象语言的核心是类。Swift 中的函数具有函数式语言中的函数的所有特点。这种支持使得开发者可以很容易地使用 Swift 写出函数式风格的代码。
惰性计算是函数式编程语言的一个特性。在使用惰性计算时,表达式不在它被绑定到变量之后就立即求值,而是在该值被调用的时候求值。与延迟存储属性有点类似。
let res = 1...3let seq = res.lazy.map {(i: Int) -> Int inprint("mapping \(i)")return i * 2}print(type(of: seq)) // LazyMapCollection<ClosedRange<Int>, Int>for i in seq {print(i)}// mapping 1// 2// mapping 2// 4// mapping 3// 6
菲波那契数列:1, 1, 2, 3, 5, 8, 13, 21, 34
class FibonacciGenerator: GeneratorType {typealias Element = Intvar current = 0, nextValue = 1func next() -> Element? {print("NEXT: ", current, nextValue)let ret = currentcurrent = nextValuenextValue += retreturn ret}}var generator = FibonacciGenerator()for _ in 1..<10 {print(generator.next()!)}
参考:
