Swift 3中的Fibonacci数字生成器

前端之家收集整理的这篇文章主要介绍了Swift 3中的Fibonacci数字生成器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的Q& A介绍了一些在Swift中生成Fibonacci数的方法,但它已经过时了(Swift 1.2?):

> Sum of Fibonacci term using Functional Swift

问题:我们如何使用现代Swift(Swift> = 3)整齐地生成斐波纳契数?优选地,避免显式递归的方法.

Swift 3.0的另一种选择是使用辅助函数
  1. public func sequence<T>(first: T,while condition: @escaping (T)-> Bool,next: @escaping (T) -> T) -> UnfoldSequence<T,T> {
  2. let nextState = { (state: inout T) -> T? in
  3. // Return `nil` if condition is no longer satisfied:
  4. guard condition(state) else { return nil }
  5. // Update current value _after_ returning from this call:
  6. defer { state = next(state) }
  7. // Return current value:
  8. return state
  9. }
  10. return sequence(state: first,next: nextState)
  11. }

Express for loops in swift with dynamic range

  1. for f in sequence(first: (0,1),while: { $1 <= 50 },next: { ($1,$0 + $1)}) {
  2. print(f.1)
  3. }
  4. // 1 1 2 3 5 8 13 21 34

请注意,为了在结果序列中包含零,它
足以用(1,0)替换初始值(0,1):

  1. for f in sequence(first: (1,0),$0 + $1)}) {
  2. print(f.1)
  3. }
  4. // 0 1 1 2 3 5 8 13 21 34

这使得“人为”检查

  1. if pair.1 == 0 { pair.1 = 1; return 0 }

多余的.根本原因是Fibonacci数字可以
推广到负指数(https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers):

  1. ... -8,5,-3,2,-1,1,3,8,...

猜你在找的Swift相关文章