简体   繁体   中英

Why i got an Error by using a Class in Swift Playgrounds

I tryed to use a class with the type Timer to repeat a while clause with a delay in swift Playgrounds but i got the error:

Declaration is expected!

What can i do?

class LedAnimation: Timer { 

    while ledAnimationVarible < 16 {
    allCircles[ledAnimationVarible].color = .blue
        ledAnimationVarible += 1
    }

}

This is not a valid class. Your code within the class should be defined within a function

class LedAnimation: Timer { 

    func animateLed(ledAnimationVarible: Int) {
        while ledAnimationVarible < 16 {
            allCircles[ledAnimationVarible].color = .blue
            ledAnimationVarible += 1
        }
    }

}

The issue is that you cannot just write executable code outside functions. You need to enclose your while loop in a function.

class LedAnimation {
   func animateLeds(){
       while ledAnimationVarible < 16 {
           allCircles[ledAnimationVarible].color = .blue
           ledAnimationVarible += 1
       }
   }
}

However, you also shouldn't subclass Timer as the documentation clearly states.

You receive the following error because while statement cannot be located in class body.

Wrap it to a function

class LedAnimation: Timer {

    func foo() {
        while ledAnimationVarible < 16 {
            allCircles[ledAnimationVarible].color = .blue
            ledAnimationVarible += 1
        }
    }

}

Your executable statements are not placed inside any executable scope. You need a function to wrap your executable statements.

class LedAnimation: Timer {

    func doSomething()
    {
        while ledAnimationVarible < 16 {
            allCircles[ledAnimationVarible].color = .blue
            ledAnimationVarible += 1
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM