Ronny Webers
Ronny Webers

Reputation: 5244

Break an (accidental) endless loop in a swift playground

while playing around in a swift playground (what's in a name), I accidentally entered an endless loop, such like this one :

var l = 3
while (l > 2) {
  println(l)
  l++
}

this causes the playground to endlessly print to the console, upon which Xcode gets stuck

The only way I found was to kill Xcode through the terminal window, however I would expect there is some more elegant way to 'stop' the playground from executing?

Upvotes: 9

Views: 8834

Answers (3)

t1ser
t1ser

Reputation: 1624

This is Xcode 8.3.3. I did not check previous versions.

While the playground is running, the source code is still editable. Just change the loop, type in a command, for example break into the code, inside the loop. This is interpreted code not compiled code so it will take effect.

Upvotes: 2

user5718828
user5718828

Reputation: 1

I was able to halt my loop by typing the iteration variable setting (that would stop the loop) somewhere else like in a text editor then right click pasting the text into the loop.

In your case, right-click pasting l = 0 right before the last bracket should work.

Upvotes: 0

Sassan Sanei
Sassan Sanei

Reputation: 71

Playground is operating exactly as designed, but it really should have a means of instantly halting execution while editing code. I have entered endless loops in mid-edit the same way as you, and it usually happens while editing the conditions in a for or while loop.

I work around this limitation by deliberately typing a few characters of gibberish on the line I am editing, or on a separate line if editing multiple lines. Playground will choke on the gibberish and stop executing the code. When I finish editing, I remove the gibberish so that Playground can execute the code once again.

For example, if I want to edit this line:

for var j=0;j<10000000;j=j+1000 {

I will first add gibberish to the end:

for var j=0;j<10000000;j=j+1000 { adsklfasd

then I will make my edits:

for var j=0;j<500;j=j+10 { adsklfasd

then i will remove the gibberish, leaving behind only the good code:

for var j=0;j<500;j=j+10 {

Playground won't execute as long as the adsklfasd is in there.

The gibberish doesn't have to go at the end of the for statement; you could put it on a separate line, if you prefer.

It's not an elegant solution, but it's fast and easy and it works. Hope this helps.

Upvotes: 6

Related Questions