Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in Swift

Tags:

for-loop

swift

Suddenly the for loop structure I learned at Apple's documentation stopped working, it shows an error: Expected declaration. Can anyone tell me what's the new syntax?

let CirclePoints = 84

var circlePoint = 0

for circlePoint in 0..<CirclePoints {

}

This way also didn't work:

for var circlePoint = 0; circlePoint < CirclePoints; circlePoint++ {

}
like image 406
vyudi Avatar asked Aug 05 '14 00:08

vyudi


1 Answers

Like the others have said, your code works fine on its own. If you're getting the error expected declaration, you may have written code inside your class body like this:

class myClass{
let CirclePoints = 84

var circlePoint = 0

for circlePoint in 0..<CirclePoints {

}

}

You can declare and set variables in the scope of the class, but all other logic must go inside methods. If you want that for loop to execute when an instance of the class is created, you can put it in the init method for the class.

class myClass{
    let CirclePoints = 84
    var circlePoint = 0

    init(){
        for circlePoint in 0..<CirclePoints {

        }
    }
}
like image 60
Connor Avatar answered Sep 17 '22 20:09

Connor