Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 378
Ronny Webers Avatar asked Nov 04 '14 21:11

Ronny Webers


People also ask

How do you stop an infinite loop in Swift playground?

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. Save this answer.

What is infinite loop in Swift?

Infinite loops are program loops that continue effectively forever. In Swift, they look like this: while true { print("I'm alive!") } print("I've snuffed it!")

How do I run a playground in Xcode?

Simply click the Run button at the bottom-right of the playground, and wait for execution to complete. Xcode now compiles your code, and shows you its result. The default code doesn't output anything to the Console, but you should be able to see the value of the variable str in the sidebar on the right of Xcode.


1 Answers

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.

like image 80
Sassan Sanei Avatar answered Oct 06 '22 00:10

Sassan Sanei