为什么我会收到错误:"在初始化之前被一个闭包捕获"?

时间:2015-07-20 12:05:35

标签: swift sprite-kit

我一直在研究这个结构,出于某种原因,当我使用特定常量创建一个if语句时,我得到了错误:

  

"在初始化之前被一个闭包捕获"

这是我的代码:

struct Block {

    let firstSquareIndex: Int
    let secondSquareIndex: Int
    let firstSquareColor: Color
    let secondSquareColor: Color
    var blockNode: SKNode
    var firstSquare: SquareNode
    var secondSquare: SquareNode

    init() {
        // create 2 different random integers 0-3
        firstSquareIndex = Int(arc4random_uniform(4))
        secondSquareIndex = Int(arc4random_uniform(4))
        while secondSquareIndex == firstSquareIndex {
            secondSquareIndex == Int(arc4random_uniform(4))
        }

        var firstRandomColorIndex = Int(arc4random_uniform(3))
        switch firstRandomColorIndex {
        case 0:
            self.firstSquareColor = Color.White
        case 1:
            self.firstSquareColor = Color.Red
        case 2:
            self.firstSquareColor = Color.Blue
        default:
            self.firstSquareColor = Color.Unspecified
            break
        }

        if firstSquareIndex - 1 == secondSquareIndex || firstSquareIndex + 1 == secondSquareIndex {
            var secondRandomColorIndex = Int(arc4random_uniform(2))
            switch self.firstSquareColor {

            case .White:
                if secondRandomColorIndex == 0 {

                    secondSquareColor = Color.Red
                }else {

                    secondSquareColor = Color.Blue
                }
            case .Red:
                if secondRandomColorIndex == 0 {

                    secondSquareColor = Color.White
                }else {

                    secondSquareColor = Color.Blue
                }
            case .Blue:
                if secondRandomColorIndex == 0 {

                    secondSquareColor = Color.White
                }else {

                    secondSquareColor = Color.Red
                }
            default:
                break
            }
        }
    }
}

Color是我制作的枚举,SquareNode是我制作的继承自SKSpriteNode的类。

错误在这一行:

if firstSquareIndex - 1 == secondSquareIndex || firstSquareIndex + 1 == secondSquareIndex {

,箭头指向第二个 firstSquareIndex 。当我用数字替换它时,错误消失了。这是确切的错误消息:

  

"变量' self.secondSquareColor'在被初始化之前由关闭捕获"

P.S。

我知道我还没有初始化所有属性,所以我也收到了错误"从初始化程序返回而没有初始化所有存储的属性" ,但那只是因为我没有写完结构。

稍微更改了代码,但问题仍然存在。 的 Full Source Code

0 个答案:

没有答案