[swift-users] Using defer in Swift Playgrounds

Joe DeCapo snoogansbc at gmail.com
Fri Aug 4 14:41:03 CDT 2017


Hi everyone,

I'm not sure if there's a more appropriate place to ask this question, but I figured at the very least I could get pointed in the right direction. I've tried searching online and haven't been able to find anything addressing this.

I was trying to use the `defer` statement in a Playground, and was surprised to find that it never prints anything in the preview pane on the side. I was expecting the evaluation of the code in the `defer` statement to show up in line with the statements, even though they're executed after the last line in the function. I made a very simple playground that modifies a global variable and prints the value in the `defer` statement, and when I print the global variable after calling my function it shows the correct updated value, so the code in the `defer` statement is getting run as expected. Here's my sample code with the Playground output in comments on the side:

var x = 3			// 3
func doSomething() {
   print(1)			// "1\n"
   defer {
       x += 1
       print(x)
   }
   print(2)			// "2\n"
}
doSomething()
print(x)			// "4\n"

I was expecting something like this:

var x = 3			// 3
func doSomething() {
   print(1)			// "1\n"
   defer {
       x += 1			// 4
       print(x)			// "4\n"
   }
   print(2)			// "2\n"
}
doSomething()
print(x)			// "4\n"

Is there some deep reason why code in `defer` statements doesn't show anything in the preview pane in Playgrounds?

-Joe

-------------- next part --------------
A non-text attachment was scrubbed...
Name: Defer.playground.zip
Type: application/zip
Size: 11739 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170804/eeb6dcba/attachment.zip>
-------------- next part --------------




More information about the swift-users mailing list