问题
I've noticed that Playgrounds in Xcode 10 no longer allow for the use of declared, but uninitialized variables. For example: while this code would work in an Xcode 9 playground, in an Xcode 10 playground (at least in Beta 1), it crashes:
var myValue: Int
//...
myValue = 100
print (myValue)
// Xcode 9 prints 100
// Xcode 10 reports an error: variables currently must have an initial value when entered at the top level of the REPL
Is this the new behavior, or just a bug in the current Xcode 10 beta?
I had been referring to earlier Xcode Playgrounds as an interpreter, but would one still consider Xcode 10 playgrounds to be an interpreter (and was that always correct)? Apple refers to the "Run" button in the gutter as "compiling" code.
Thanks!
回答1:
I hit this error. I had two different playgrounds up, one had the error and one did not. The issue was that "Automatically Run" was not set for my playground. To set the option, click on the play arrow at the top of the debug window in your playground and you will see the option to "Automatically Run", choose it.
Must be that Automatically Run mode is more like running an entire program, whereas manual run is not.
回答2:
1) The error you now get if you do not initialize the let-declared constant is new as of Xcode 10, but only in the Swift REPL or playground, not if you compile the code (see below).
2) The Swift Playgrounds REPL (Read-Eval-Print-Loop) and an interpreter are almost but not quite the same thing. The REPL is an interactive text editor that reads your code statements, executes them, and prints the results, looping as you edit the text. As you make edits in a Playground, Xcode re-executes all the code in the editor over and over again, one line at a time as if you were typing in each line every time for the first time. This is different from an interpreter only in that an interpreter generally reads code from input files, interpreting and executing it one line at a time instead of compiling & linking it all to machine code first before execution begins.
来源:https://stackoverflow.com/questions/51362893/change-in-xcode-10-playgrounds-variable-initialization-change-are-xcode-10-play