Swift 游乐场没有输出

No output in Swift Playground

我正在尝试将斐波那契数放入一个数组中,并希望在 playground 控制台中查看数组输出,但由于某种原因我没有看到任何输出。有人可以帮助我理解我在程序中犯的错误吗?

import UIKit

class FibonacciSequence {

    let includesZero: Bool
    let values: [Int]

    init(maxNumber: Int, includesZero: Bool) {
        self.includesZero = includesZero
        values = [0]
        var counter: Int
        if (includesZero == true) { counter = 0 }
        else { counter = 1 }
        for counter  <= maxNumber; {
            if ( counter == 0 ) {
                values.append(0)
                counter = 1
            }
            else {
                counter = counter + counter
                values.append(counter)
            }
        }
        println(values)

    }

    println(values)
    return values
}

let fibanocciSequence = FibonacciSequence(maxNumber:123, includesZero: true)

你的问题是你的代码有错误;如果您的代码中有错误,Playgrounds 将不会 运行 它并且您不会得到任何输出。

  • 在行 for counter <= maxNumber; 你有一个分号,而且,我很确定你不能像那样声明一个 for 循环,除非我遗漏了什么?不过,您可以使用 while 循环。

  • 你为什么要从你的 init 方法中 return values

  • 您已将 values 声明为常量,但随后试图使用 append 更改它。

  • 使用此代码并修复所述错误不会生成斐波那契数列,而是生成:[0, 0, 2, 4, 8, 16, 32, 64, 128]

试试这个代码:

class FibonacciSequence {
    let values: [Int]

    init(maxNumber: Int, includesZero: Bool) {
        var tempValues = includesZero ? [0] : [1]
        var current = 1

        do {
            tempValues.append(current)

            let nMinus2 = tempValues[tempValues.count - 2]
            let nMinus1 = tempValues[tempValues.count - 1]

            current = nMinus2 + nMinus1

        } while current <= maxNumber

        self.values = tempValues
    }
}

然后创建一个实例:

let fibanocciSequence = FibonacciSequence(maxNumber:123, includesZero: true)
println(fibanocciSequence.values) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

希望对您有所帮助!

@ABakerSmith 已按原样为您提供了代码中问题的详细概述,但您可能还需要考虑,而不是 class 来初始化数组成员变量,编写 SequenceType returns 斐波纳契数:

struct FibonacciSequence: SequenceType {
    let maxNumber: Int
    let includesZero: Bool

    func generate() -> GeneratorOf<Int> {
        var (i, j) = includesZero ? (0,1) : (1,1)
        return GeneratorOf {
            (i, j) = (j, i+j)
            return (i < self.maxNumber) ? i : nil
        }
    }
}

let seq = FibonacciSequence(maxNumber: 20, includesZero: false)

// no arrays were harmed in the generation of this for loop
for num in seq {
    println(num)
}

// if you want it in array form:
let array = Array(seq)

如果你想提高多代性能,你当然可以记住序列。