[swift-users] Using defer in Swift Playgrounds

Jordan Rose jordan_rose at apple.com
Mon Aug 7 15:23:30 CDT 2017


Either way is fine. I suspect this is a bug with the transformation the Swift compiler performs when compiling for a playground, rather than with the machinery that goes with running the playground, but I haven’t looked into it.

Jordan


> On Aug 7, 2017, at 13:22, Joe DeCapo <snoogansbc at gmail.com> wrote:
> 
> Since it's Playground bug, should I file it in Apple's bug reporter rather than Swift's?
> 
>> On Aug 7, 2017, at 3:12 PM, Jordan Rose <jordan_rose at apple.com> wrote:
>> 
>> I’d say that’s a bug! Mind filing it at https://bugs.swift.org ?
>> 
>> Thanks,
>> Jordan
>> 
>>> On Aug 4, 2017, at 12:41, Joe DeCapo via swift-users <swift-users at swift.org> wrote:
>>> 
>>> 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
>>> 
>>> <Defer.playground>
>>> 
>>> _______________________________________________
>>> swift-users mailing list
>>> swift-users at swift.org
>>> https://lists.swift.org/mailman/listinfo/swift-users
>> 
> 



More information about the swift-users mailing list