ios - Swift Playground 没有输出

标签 ios swift 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)

最佳答案

@ABakerSmith 已按原样为您提供了代码中问题的简要概述,但您可能还想考虑编写 SequenceType 来代替初始化数组成员变量的类返回斐波那契数:

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)

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

关于ios - Swift Playground 没有输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753278/

相关文章:

ios - 在 SWIFT 中处理 UIActionSheet 上的事件

javascript - 苹果音乐 API 引用

ios - 我正在尝试从我的 ios Swift 项目中的 Firestore 数据库中获取数据

swift - 我怎样才能将图像获取到某个 imageView,它位于另一个 Viewcontroller 中,并且尚未创建(为零)

xcode - 无法强制解包非可选类型的值 : Avoid "Optional()"

ios - 如何获取数组中UITextView的所有单词的NSRange值?

swift - didSelectRowAt indexPath 在点击时不触发(但在向任一方向滑动单元格时触发)

ios - 我的带有自动布局约束的 Swift 4 UIScrollView 不滚动

xcode - Playground Xcode 7.2.1 中无法访问图像资源

ios - 无法在 SWIFT 中的方法之外保留数组数据