下面的Q& A介绍了一些在Swift中生成Fibonacci数的方法,但它已经过时了(Swift 1.2?):
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 loops in swift with dynamic range:
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
请注意,为了在结果序列中包含零,它
足以用(1,0)替换初始值(0,1):
for f in sequence(first: (1,0),$0 + $1)}) { print(f.1) } // 0 1 1 2 3 5 8 13 21 34
这使得“人为”检查
if pair.1 == 0 { pair.1 = 1; return 0 }
多余的.根本原因是Fibonacci数字可以
推广到负指数(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):
... -8,5,-3,2,-1,1,3,8,...