简体   繁体   中英

Swift equivalent for while loops with else in python

I have the following code written in Swift

        if current_game_state == game_state.in_game {
            while player_card_values.sum() <= 20 {
                for touch: AnyObject in touches {
                    let point_of_touch = touch.location(in: self)
                    if hit_label.contains(point_of_touch){
                        spawn_card()
                        print("Hit Button Pressed")
                    }
                }
            }
            else {
                if self.player_card_values.sum() == 21 {
                    print("Player has received BJ!")
                    self.player_status = person_status.stand
                    break
                }
            }
                for touch: AnyObject in touches {
                    let point_of_touch = touch.location(in: self)
                    if stand_label.contains(point_of_touch){
                        print("Stand Button Pressed")
                        player_status = person_status.stand
                        
                    }
                }
            }
        }

All inside touchesBegan in Spritekit. But for some reason, I am getting two errors when trying to compile this.

  1. Closure expression is unused, on the line where it says else. Not sure why because the expression is not unused, as there is code inside it.
  2. Unlabeled break is only allowed inside a loop or a switch, a labeled break is required to exit and if or a do. I'm confused here-- what's the difference between an unlabeled and labeled break? And the else statement is in response to the while loop, if the sum of the playercardvals is greater than 20

There is no while ... else ... in Swift, you will have to refactor your logic.

Also, you do not want to loop inside touchesBegan your app will stop responding!

Closure expression is unused, on the line where it says else. Not sure why because the expression is not unused, as there is code inside it.

You have else right after where your while block ends. It makes sense after where if / else if blocks end, not after while .


Unlabeled break is only allowed inside a loop or a switch, a labeled break is required to exit and if or a do.

Your else block that contains the break is not a part of the while body.


You need to regroup your code, you have misplaced } in your code and it is not making sense to the compiler.

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