[swift-users] Inconsistent behaviour of forward declarations

Joshua Scott Emmons skia at skia.net
Sun Jan 10 08:55:37 CST 2016


> 
> You are right Dan. I did give it a try previously from the REPL. And yes, fails if scripted. 

I think what you're running into here is the different ways the REPL, Playgrounds, and .swift files are initialized (esp. with respect to globals). There's some interesting talk about this on the (original) Swift blog at Apple: https://developer.apple.com/swift/blog/#article-18

"Most Swift files in your app are order-independent, meaning you can use a type before it is defined, and can even import modules at the bottom of the file (although that is not recommended Swift style.)"

"Code within a playground file is order-dependent, run in top-down lexical order. For example, you can’t use a type before you define it."

"The exception is a special file named “main.swift”, which behaves much like a playground file, but is built with your app’s source code. "

"Given how Swift determines where to start executing an app, how should global variables work? ... In a single-file program, code is executed top-down, similar to the behavior of variables within a function. Pretty simple. The answer for complex apps is less obvious... [Swift] runs the initializer for a global the first time it is referenced, similar to Java ... which is the best of all worlds: it allows custom initializers, startup time in Swift scales cleanly with no global initializers to slow it down, and the order of execution is completely predictable."

This was from back in beta days, but I'm pretty sure it still applies.

-- 
Cheers!
-jemmons
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160110/52b3e3e7/attachment.html>


More information about the swift-users mailing list