以下问答涵盖了几种在Swift中生成斐波那契数的方法,但已经过时了(Swift 1.2?) 问题: 如何使用现代Swift(Swift> = 3)整齐地生成斐波那契数?最好是避免显式递归的方法。
Swift 3.0的替代方法是使用助手功能
public func sequence<T>(first: T, while condition: @escaping (T)-> Bool, next: @escaping (T) -> T) -> UnfoldSequence<T, T> { let nextState = { (state: inout T) -> T? in // Return `nil` if condition is no longer satisfied: guard condition(state) else { return nil } // Update current value _after_ returning from this call: defer { state = next(state) } // Return current value: return state } return sequence(state: first, next: nextState) }
从Express for动态循环迅速变化:
for f in sequence(first: (0, 1), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) { print(f.1) } // 1 1 2 3 5 8 13 21 34
注意,为了以包括所产生的序列中的零,只要更换的初始值(0, 1)由(1, 0):
(0, 1)
(1, 0)
for f in sequence(first: (1, 0), while: { $1 <= 50 }, next: { ($1, $0 + $1)}) { print(f.1) } // 0 1 1 2 3 5 8 13 21 34
这使得“人为”检查
if pair.1 == 0 { pair.1 = 1; return 0 }
多余的。根本原因是斐波那契数可以归纳为负索引(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):
... -8, 5, -3, 2, -1, 1, 0, 1, 1, 2, 3, 5, 8, ...